1

我正在尝试将图像大小调整为 50 * 50 像素。我从存储在数据库中的路径中获取图像。获取图像并显示它们没有问题。我只是想知道我应该在什么时候尝试调整图像大小。应该是当我将图像作为缓冲图像获取时,还是只是尝试调整图标大小?

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

上面的代码是检索图像并将其分配给 ImageIcon,然后是 JLabel。我试图通过使用下面的调整大小方法来调整缓冲图像的大小。你们能解释一下为什么这对我不起作用吗?没有出现任何错误,只是图像保持其原始大小。

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

1 回答 1

5

您在每个图像上调用 resize() ,但不替换数组中的图像。所以 resize() 的输出被丢弃了:

 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

您需要将中间线更改为:

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

使这项工作。

于 2012-02-22T21:59:50.420 回答