我的MySQL中有一个blob类型字段,我想将数据放在JLabel
中的这个字段中作为Icon。例如,JLabel
将是我表单中用户的个人资料图片。
我使用了这些代码但没有任何反应
我还希望fix to width
或修复我的jlabel中的任何图像尺寸
DefaultTableModel pic = MyDB.DataTable("SELECT `Picture` FROM `photo` WHERE `Employee ID` = 'EQ0103'");
if (pic.getRowCount() > 0){
Blob blob = pic.getBlob(1);
byte[] image1 = blob.getBytes(1, ALLBITS);
ImageIcon image = new ImageIcon(image1);
picture.setIcon(image);
getContentPane().add(picture);
setVisible(true);
}
picture
是我的jlabel
答案 0 :(得分:6)
首先:从数据库中返回输入流:
String query = "SELECT `Picture` FROM `photo` WHERE `Employee ID` = 'EQ0103'";
stmt = (PreparedStatement) con.prepareStatement(query);
ResultSet result = stmt.executeQuery();
从数据库返回的图片
BufferedImage im = ImageIO.read(result.getBinaryStream(1));
然后重新调整此图片:
im =linearResizeBi(im, /*width*/, /*height*/);
linearResizeBi 方法:
static public BufferedImage linearResizeBi(BufferedImage origin, int width, int height) {
BufferedImage resizedImage = new BufferedImage(width, height ,BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
float xScale = (float)width / origin.getWidth();
float yScale = (float)height / origin.getHeight();
AffineTransform at = AffineTransform.getScaleInstance(xScale,yScale);
g.drawRenderedImage(origin,at);
g.dispose();
return resizedImage;
}
然后将图片设为图标:
ImageIcon image1 = new ImageIcon(im);
然后将图标添加到Jlabel:
picture.setIcon(image);
getContentPane().add(picture);
setVisible(true);
答案 1 :(得分:1)
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT `Picture` FROM `photo` WHERE `Employee ID` = 'EQ0103'");
您可以从
更改Blob blob = rs.getBlob(1);
另一个
的替代InputStream binaryStream = rs.getBinaryStream(1);
您可以参考此处从博客获取图片的官方指南 http://docs.oracle.com/javase/1.5.0/docs/guide/jdbc/blob.html
答案 2 :(得分:1)
txtPicPath.setText(file.getAbsoluteFile().toString());
我使用了这些代码,并且它符合jlabel大小
ResultSet rst = MyDB.rsFetch("SELECT `Picture` FROM `photo` WHERE `Employee ID` = '"+ Data.User.getText()+"'");
while (rst.next()) {
Blob filenameBlob = rst.getBlob("Picture");
byte[] content = filenameBlob.getBytes(1L,(int)filenameBlob.length());
ImageIcon ik = new ImageIcon(content);
Image img = ik.getImage();
Image newimg = img.getScaledInstance(Data.picture.getWidth(), Data.picture.getHeight(), java.awt.Image.SCALE_SMOOTH);
ik = new ImageIcon(newimg);
Data.picture.setIcon(ik);
}
答案 3 :(得分:0)
Blob有一个getBinaryStream(),它返回一个包含blob中存储数据的字节流。
实现Icon的ImageIcon有一个构造函数,它以字节数组作为参数。
JLabel有一个setIcon(Icon)方法。
label.setIcon(new ImageIcon(ByteStreams.toByteArray(blob.getBinaryStream())));
答案 4 :(得分:0)
尝试:
picture.setIcon(new ImageIcon(ByteStreams.toByteArray(blob.getBinaryStream())));