tags:

views:

397

answers:

2

I resized the picture into 100x100 size by using Graphics class and drawImage() method. But i can't load the resized the image into JLabel. Is possible to load a resized picture into JLabel?

Image image   =   jfc.getSelectedFile();
ImageIcon Logo   =   new ImageIcon(image.getPath());
BufferedImage resizedImage = new BufferedImage(width, height, 
BufferedImage.TYPE_INT_ARGB); 
Graphics2D g = resizedImage.createGraphics();
g.drawImage(image, 0, 0, 100, 100, null); // Here i resized. But after that how can i load into Jlabel?

JLabel labelLogo;
labelLogo.setIcon(Logo);
...?
+1  A: 

Hi, here is an example: you possibliy need to update the layout after modifying the component in actionPerformed().

public static void main(String[] args) {
    JFrame frame = new JFrame();
    final Container panel = frame.getContentPane();
    panel.setLayout(new FlowLayout());

    // create an image an draw in it.
    final BufferedImage image = new BufferedImage(
        200, 200, BufferedImage.TYPE_INT_ARGB);
    Graphics g = image.getGraphics();
    g.setColor(Color.RED);
    g.drawLine(0, 0, image.getWidth(), image.getHeight());

    Icon iImage = new ImageIcon(image);
    // create a label with the icon.
    final JLabel label = new JLabel(iImage);
    panel.add(label);
    // create a new button.
    JButton button = new JButton("resize");
    // add an action to the button.
    button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            // set the label with a new icon.
            BufferedImage bi = new BufferedImage(
                100, 100, BufferedImage.TYPE_INT_ARGB);
            bi.getGraphics().drawImage(image, 0, 0, null);
            label.setIcon(new ImageIcon(bi));
        }
    });
    // add the button to the frame.
    panel.add(button);
    // open the frame.
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}
elou
oh, this article said not to use getScaledInstance... http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html
ultrajohn
thx for the article.
elou
trashgod
A: 

this article said something about avoiding the use of getScaledInstance method, and also provided some alternative approach...

link to article

ultrajohn
exemple corrected.
elou