Autoresize the image using imageicon on jlabel

1.6k Views Asked by At

I need to fit the image on jlabel, my images are stored in MySql table and I getting those using following code -

byte[] imagedata=rs.getBytes(6); // rs is ResultSet of table
format=new ImageIcon(imagedata);
jLabel15.setIcon(format);

How can I resize the "format" which I want to display on jLabel15.

Edited: Image column in table is bigblob data type

3

There are 3 best solutions below

0
On BEST ANSWER

you can scale your image the following way,

    Image img = format.getImage().getScaledInstance(50, 50, Image.SCALE_SMOOTH);
    jLabel15.setIcon(new ImageIcon(img));

I have scalled the image to 50X50 you can scale it to your desired size

0
On

One way I suppose is to override the ImageIcon's paintIcon(...) method, to resize the image if the icon itself is resized.

0
On

Here is an example how to resize the image on resize of the component.

import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;

public class ResizedLabelTest {

    public static void main(String[] args) throws Exception {
        JFrame frm = new JFrame("ResizedLabel test");
        URL url = new URL("https://i.stack.imgur.com/37IMZ.jpg?s=128&g=1");
        final ImageIcon icon = new ImageIcon(url);
        JLabel label = new JLabel(icon);
        label.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                JLabel label = (JLabel) e.getComponent();
                Dimension size = label.getSize();
                Image resized = icon.getImage().getScaledInstance(size.width, size.height, Image.SCALE_SMOOTH);
                label.setIcon(new ImageIcon(resized));
            }
        });
        frm.add(label);
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.pack();
        frm.setVisible(true);
    }
}