重新调整jLabel上的图像大小

时间:2012-10-16 07:50:15

标签: java image resize jlabel autoresize

我试图在java中的jLabel上调整图像大小,下面给出了无效代码的片段:

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

我无法找到我错在哪里。请建议我如何处理它。

由于

2 个答案:

答案 0 :(得分:2)

请参阅下面的重新缩放图像的更好解决方案。在下面的代码中,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();

答案 1 :(得分:1)

以下是渲染组件的代码,可能会为您提供一些提示。

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