保存已调整大小的图像java

时间:2012-09-27 11:19:40

标签: java image swing javax.imageio imageicon

如何将已调整大小的图像保存到特定文件夹?

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    ImgChooser ic = new ImgChooser();
    ImageIcon icon = new ImageIcon(me,"id pic");
    Image img1 = icon.getImage();
    Image img2 = img1.getScaledInstance(105, 105, 0);
    icon.setImage(img2);
    jLabel1.setIcon(icon);
} 

这第一个代码是我获取图像并调整大小的地方。然后我希望调整大小的图像保存在另一个文件夹中。提前致谢

3 个答案:

答案 0 :(得分:7)

使用ImageIO.write(...)正如其他人已经说过的那样(+1给他们),这里添加的是一个例子:

public static void main(String[] args) {

    try {

        BufferedImage originalImage = ImageIO.read(new File("c:\\test.jpg"));//change path to where file is located
        int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();

        BufferedImage resizeImageJpg = resizeImage(originalImage, type, 100, 100);
        ImageIO.write(resizeImageJpg, "jpg", new File("c:\\images\\testresized.jpg")); //change path where you want it saved

    } catch (IOException e) {
        System.out.println(e.getMessage());
    }

}

private static BufferedImage resizeImage(BufferedImage originalImage, int type, int IMG_WIDTH, int IMG_HEIGHT) {
    BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
    Graphics2D g = resizedImage.createGraphics();
    g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
    g.dispose();

    return resizedImage;
}

<强>参考:

答案 1 :(得分:4)

试试这个......

使用ImageIO.write()方法......

static boolean ImageIO.write(RenderedImage im, String formatName, File output) throws IOException

<强>例如

try {

    // retrieve image

    BufferedImage bi = getMyImage();
    File outputfile = new File("saved.png");
    ImageIO.write(bi, "png", outputfile);

} catch (IOException e) {
    ...
}

答案 2 :(得分:3)

首先将您的图片转换为BufferedImage,然后使用ImageIO保存图片:

BufferedImage image = new BufferedImage(img2.getWidth(null), img2.getHeight(null), BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2 = image.createGraphics();
g2.drawImage(img2, 0, 0, null);
g2.dispose();
ImageIO.write(image, formatName, outputFile);

如果格式名称为String,例如"jpg",则"png""gif"outputFile是将File保存为BufferedImage

另请注意,如果要保存不支持Alpha级别(透明度)的图像,则传递给BufferedImage.TYPE_3BYTE_BGR构造函数的第三个参数应为3字节图像,如:{{1} }