MySQL的BLOB Netbeans需要的JLabel(MySQL blob to Netbean

2019-07-21 16:44发布

我在MySQL中的BLOB类型字段,我想把数据在这一领域JLabel的图标。 例如,这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的名称

Answer 1:

首先:从数据库返回的输入流:

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));

然后,让rezise到该图像:

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);


Answer 2:

使用结果集

 Statement stmt = con.createStatement();
 ResultSet rs = stmt.executeQuery("SELECT `Picture` FROM `photo` WHERE `Employee ID` = 'EQ0103'");

你可以从改变

Blob blob = rs.getBlob(1);

到另一个altenative

InputStream binaryStream = rs.getBinaryStream(1);

你可以参考获得图像的官方指南从这里博客http://docs.oracle.com/javase/1.5.0/docs/guide/jdbc/blob.html



Answer 3:

我有我的文件名应该是这样的

  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);
         }


Answer 4:

斑点具有getBinaryStream()返回包含存储在所述团块中的数据的字节流。

的ImageIcon,它实现图标,有一个构造这需要一个字节数组作为参数。

JLabel的拥有的setIcon(图标)方法。

label.setIcon(new ImageIcon(ByteStreams.toByteArray(blob.getBinaryStream())));


Answer 5:

尝试:

picture.setIcon(new ImageIcon(ByteStreams.toByteArray(blob.getBinaryStream())));


文章来源: MySQL blob to Netbeans JLabel