Peddler
Peddler

Reputation: 6085

Resize the ImageIcon or the Buffered Image?

I'm trying to resize an image to 50 * 50 pixels. Im taking the images, from their path stored in a Database. I have no problem getting the images and displaying them. I'm just wondering at what point should I try resize the images. Should it be when I get the image as a buffered image, or just try to resize the icon?

while (rs.next()) {
                        i = 1;
                        imagePath = rs.getString("path");
                            System.out.println(imagePath + "\n");
                            System.out.println("TESTING - READING IMAGE");
                        System.out.println(i);

                        myImages[i] = ImageIO.read(new File(imagePath));
                        **resize(myImages[i]);**

                        imglab[i] = new JLabel(new ImageIcon(myImages[i]));
                        System.out.println(i);
                        imgPanel[i]= new JPanel();
                        imgPanel[i].add(imglab[i]);
                        loadcard.add(imgPanel[i], ""+i);     
                        i++; 

The above code is retrieving the image and assigning it to an ImageIcon, then JLabel. I have attempted to resize the buffered image, by using the below resize method. Could you guys, shed any light on why this isn't working for me? Not getting any errors, just the image remains its original size.

public static BufferedImage resize(BufferedImage img) {  
          int w = img.getWidth();  
          int h = img.getHeight(); 
          int newH = 50;
          int newW = 50;
          BufferedImage dimg = dimg = new BufferedImage(newW, newH, img.getType());  
          Graphics2D g = dimg.createGraphics();  
          System.out.println("Is this getting here at all " + dimg);
          g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);  
          g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);  
          g.dispose();  
          return dimg;
          }

Upvotes: 1

Views: 1728

Answers (1)

DNA
DNA

Reputation: 42617

You are calling resize() on each image, but not replacing the images in the array. So the output of resize() is being thrown away:

 myImages[i] = ImageIO.read(new File(imagePath)); // create an image
 resize(myImages[i]); // returns resized img, but doesn't assign it to anything
 imglab[i] = new JLabel(new ImageIcon(myImages[i])); // uses _original_ img

You need to change the middle line to:

 myImages[i] = resize(myImages[i]);

to make this work.

Upvotes: 5

Related Questions