【问题标题】:Re sizing an image on a jLabel在 jLabel 上调整图像大小
【发布时间】:2012-10-06 06:27:27
【问题描述】:

我试图在 java 中调整 jLabel 上的图像大小,下面给出了不起作用的代码的 sn-p:

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

当我运行它时,我的 jlabel 上什么也没有。事实上,如果我运行下面的代码,它工作正常。问题是我想要一个按比例缩小的图像:

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

我找不到我错的地方。请建议我任何想法我应该如何去做。

谢谢

【问题讨论】:

标签: java image resize jlabel autoresize


【解决方案1】:

请参阅下面的重新缩放图像的更好解决方案。在下面的代码中,newImage 是重新缩放的图像。

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();

【讨论】:

    【解决方案2】:

    这里是渲染组件的代码,可能会给你一些提示。

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

    【讨论】:

      猜你喜欢
      • 2014-05-05
      • 1970-01-01
      • 2015-01-21
      • 1970-01-01
      • 2013-10-12
      • 1970-01-01
      • 2021-07-20
      • 2021-08-15
      相关资源
      最近更新 更多