MySQL blob到Netbeans JLabel

kel*_*vzy 0 java swing netbeans blob jlabel

我的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);
     }
Run Code Online (Sandbox Code Playgroud)

picture 是我的jlabel的名字

Aly*_*mal 6

第一步:从数据库返回输入流:

String query = "SELECT `Picture` FROM `photo` WHERE `Employee ID` = 'EQ0103'";
stmt = (PreparedStatement) con.prepareStatement(query);
ResultSet result = stmt.executeQuery();
Run Code Online (Sandbox Code Playgroud)

从数据库返回的图像

BufferedImage im = ImageIO.read(result.getBinaryStream(1));
Run Code Online (Sandbox Code Playgroud)

然后重新调整此图像:

im =linearResizeBi(im, /*width*/, /*height*/);
Run Code Online (Sandbox Code Playgroud)

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;
    }
Run Code Online (Sandbox Code Playgroud)

然后使图像是一个图标:

ImageIcon image1 = new ImageIcon(im);

然后将图标添加到Jlabel:

picture.setIcon(image);
getContentPane().add(picture);
setVisible(true);
Run Code Online (Sandbox Code Playgroud)