save resized image java

2019-03-28 18:00发布

How do i save a resized image to a specific folder?

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

This first code is where i get the image and resize it. Then i want the resized image to be saved in another folder. Thanks in advance

3条回答
小情绪 Triste *
2楼-- · 2019-03-28 18:25

Try this...

Use ImageIO.write() method...

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

Eg:

try {

    // retrieve image

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

} catch (IOException e) {
    ...
}
查看更多
Rolldiameter
3楼-- · 2019-03-28 18:31

First transform your image into a BufferedImage and then use ImageIO to save the image:

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

Where the format name is a String like "jpg", "png" or "gif" and outputFile is the File to save the image to.

Also please note that if you are saving an image that doesn't support an alpha level (transparency) then the third parameter you pass to the BufferedImage constructor should be a 3 byte image like: BufferedImage.TYPE_3BYTE_BGR

查看更多
The star\"
4楼-- · 2019-03-28 18:44

Use ImageIO.write(...) as others have already said (+1 to them), to add here is an example for you:

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

Reference:

查看更多
登录 后发表回答