在哪里/如何调用我的resizeimage方法

时间:2014-03-30 06:05:35

标签: java resize bufferedimage graphics2d imageicon

好吧所以我创建了一个调整ImageIcon大小的方法我的问题是如何/我在哪里调用它以使ImageIcon我想调整大小到这里它是感谢,并且该方法应该工作所以任何人都在寻找调整大小的方法应该能够使用它:)

    public static void resizeIcon(ImageIcon icon, int Width, int Height){
    Image geticon = icon.getImage();
    BufferedImage bi = new BufferedImage(geticon.getWidth(null), geticon.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.createGraphics();
    g.drawImage(geticon, 0, 0, Width, Height, null);
    ImageIcon resizedicon = new ImageIcon(bi);
    icon = resizedicon;

}

1 个答案:

答案 0 :(得分:0)

首先保存已调整大小的图像。然后按资源将图像图像设置为已调整大小的图像。

public static Boolean resizeImage(String sourceImage, String destinationImage, Integer   Width, Integer Height) {
    BufferedImage origImage;
    try {

        origImage = ImageIO.read(new File(sourceImage));
        int type = origImage.getType() == 0? BufferedImage.TYPE_INT_ARGB :  origImage.getType();

        //*Special* if the width or height is 0 use image src dimensions
        if (Width == 0) {
            Width = origImage.getWidth();
        }
        if (Height == 0) {
            Height = origImage.getHeight();
        }

        int fHeight = Height;
        int fWidth = Width;

        //Work out the resized width/height
        if (origImage.getHeight() > Height || origImage.getWidth() > Width) {
            fHeight = Height;
            int wid = Width;
            float sum = (float)origImage.getWidth() / (float)origImage.getHeight();
            fWidth = Math.round(fHeight * sum);

            if (fWidth > wid) {
                //rezise again for the width this time
                fHeight = Math.round(wid/sum);
                fWidth = wid;
            }
        }

        BufferedImage resizedImage = new BufferedImage(fWidth, fHeight, type);
        Graphics2D g = resizedImage.createGraphics();
        g.setComposite(AlphaComposite.Src);

        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        g.drawImage(origImage, 0, 0, fWidth, fHeight, null);
        g.dispose();

        ImageIO.write(resizedImage, "png", new File(destinationImage));

    } catch (IOException ex) {
        System.out.println(""+ex);
        return false;
    }

    return true;
}

然后致电

ImageIcon ico = new ImageIcon(destinationImage);
labelforIcon.setIcon(ico);