1

I trying to re size an image on a jLabel in java, the snippet of the code which is not working is given below:

ImageIcon imgThisImg = new ImageIcon(rs.getString("PictureURL"));
Image image=null;
image=jLabel2.createImage(120, 50);
ImageIcon imi=new ImageIcon(image);
jLabel2.setIcon(imi);

When i run it i get nothing on my jlabel. In fact if i run the code below it works fine. The thing is that i want a scaled down image:

ImageIcon imgThisImg = new ImageIcon(rs.getString("PictureURL"));
jLabel2.setIcon(imgThisImg);                          

I cant find where i am wrong. Please suggest me any ideas how should i go about it.

Thanks

Nitesh Verma
  • 1,795
  • 4
  • 27
  • 46
  • You could try having a look at http://stackoverflow.com/questions/11959758/java-maintaining-aspect-ratio-of-jpanel-background-image/11959928#11959928 and [The Perils of Image.getScaledInstance()](http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html) – MadProgrammer Oct 16 '12 at 09:33

2 Answers2

2

Please see below a better solution for re-scaling an image. In the code below, newImage is the rescaled image.

BufferedImage image = ImageIO.read(imageFile);
BufferedImage newImage = new BufferedImage(newWidth, newHeight, image.getType());
Graphics2D g2 = newImage.createGraphics();
g2.drawImage(image, 0, 0, newWidth, newHeight, null);
g2.dispose();
Dan D.
  • 32,246
  • 5
  • 63
  • 79
1

Here is code for a rendering component that might give you some tips.

class PaintCommandListCellRenderer extends DefaultListCellRenderer {

    @Override
    public Component getListCellRendererComponent(
            JList list, 
            Object value,
            int index, 
            boolean isSelected, 
            boolean hasFocus) {
        Component c = super.getListCellRendererComponent(list, value, index, isSelected, hasFocus);
        if (c instanceof JLabel && value instanceof PaintCommand) {
            JLabel l = (JLabel)c; 
            PaintCommand pc = (PaintCommand)value;
            try {
                BufferedImage bi = pc.getUndoImage();
                double w = bi.getWidth();
                double ideal = 200d;
                double ratio = w/ideal;
                int aw = (int)(w/ratio);
                int ah = (int)(bi.getHeight()/ratio);
                BufferedImage bj = new BufferedImage(
                        aw,ah,BufferedImage.TYPE_INT_ARGB);
                Graphics2D g = bj.createGraphics();
                g.drawImage(bi, 0, 0, aw, ah, null);
                g.dispose();
                l.setIcon(new ImageIcon(bj));
                l.setText("");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return c;
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433