【问题标题】:Resize the ImageIcon or the Buffered Image?调整 ImageIcon 或缓冲图像的大小?
【发布时间】:2012-02-22 21:56:24
【问题描述】:

我正在尝试将图像大小调整为 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;
          }

【问题讨论】:

    标签: java swing resize bufferedimage imageicon


    【解决方案1】:

    您正在对每个图像调用 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]);
    

    使这项工作。

    【讨论】:

    • 抱歉,您能否更具体地说明我到底哪里出错了?
    猜你喜欢
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    相关资源
    最近更新 更多