调整ImageIcon或缓冲图像的大小?

Ped*_*ler 1 java swing bufferedimage resize imageicon

我正在尝试将图像大小调整为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++; 
Run Code Online (Sandbox Code Playgroud)

上面的代码检索图像并将其分配给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;
          }
Run Code Online (Sandbox Code Playgroud)

DNA*_*DNA 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
Run Code Online (Sandbox Code Playgroud)

您需要将中间行更改为:

 myImages[i] = resize(myImages[i]);
Run Code Online (Sandbox Code Playgroud)

使这项工作.