How to create an image from an InputStream, resize it and save it?

15,718

I did this:

try {

        InputStream is = file.getInputStream();
        Image image = ImageIO.read(is);

        BufferedImage bi = this.createResizedCopy(image, 180, 180, true);
        ImageIO.write(bi, "jpg", new File("C:\\ImagenesAlmacen\\QR\\olaKeAse.jpg"));

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

BufferedImage createResizedCopy(Image originalImage, int scaledWidth, int scaledHeight, boolean preserveAlpha) {
    int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
    BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
    Graphics2D g = scaledBI.createGraphics();
    if (preserveAlpha) {
        g.setComposite(AlphaComposite.Src);
    }
    g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
    g.dispose();
    return scaledBI;
}

And I did not use the other code.

Hope helps someone!

Share:
15,718
Kaz Miller
Author by

Kaz Miller

Love software development.

Updated on June 04, 2022

Comments

  • Kaz Miller
    Kaz Miller almost 2 years

    I have this code where i get an InputStream and create an image:

    Part file;
    // more code
    try {
            InputStream is = file.getInputStream();
    
            File f = new File("C:\\ImagenesAlmacen\\QR\\olaKeAse.jpg");
    
            OutputStream os = new FileOutputStream(f);
            byte[] buf = new byte[1024];
            int len;
    
            while ((len = is.read(buf)) > 0) {
                os.write(buf, 0, len);
            }
    
            os.close();
            is.close();
    
        } catch (IOException e) {
            System.out.println("Error");
        }
    

    The problem is that I have to resize that image before i create if from the InputStream

    So how to resize what I get from the InputStream and then create that resized image. I want to set the largest side of the image to 180px and resize the other side with that proportion.

    Example:

    Image = 289px * 206px Resized image = 180px* 128px