6

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

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

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

4

3 回答 3

9

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

参考:

于 2012-09-27T21:06:56.737 回答
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) {
    ...
}
于 2012-09-27T12:47:46.203 回答
3

首先将您的图像转换为a 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);

格式名称是Stringlike"jpg"或and是要保存图像的"png"位置。"gif"outputFileFile

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

于 2012-09-27T12:31:03.203 回答