Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

java - MySQL blob to Netbeans JLabel

I have a blob type field in my MySQL, I want to put the data in this field in JLabel as Icon. For example this JLabel will be user's Profile Picture in my form.

I used this codes but nothing happens and also I want to fix to width or fix any image size in my 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 is the name of my jlabel

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First : Return the Input stream from your database :

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

Returned image from Database

BufferedImage im = ImageIO.read(result.getBinaryStream(1));

Then make rezise to this image :

im =linearResizeBi(im, /*width*/, /*height*/);

linearResizeBi Method :

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

then make the image is an Icon:

ImageIcon image1 = new ImageIcon(im);

then add the Icon to The Jlabel :

picture.setIcon(image);
getContentPane().add(picture);
setVisible(true);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...