3

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

Kaz Miller
  • 949
  • 3
  • 22
  • 40
  • You never flush the `OutputStream`. As for the other part of your question, you can probably find an answer here: http://stackoverflow.com/questions/244164/ – blgt Jun 27 '14 at 13:01
  • @blgt Ok please help me with the flush part. I tried what the other question says. Now that I have a BufferedImage, how to save that as a jpg image here "C:\\ImagenesAlmacen\\QR\\olaKeAse.jpg"? – Kaz Miller Jun 27 '14 at 13:17
  • By doing exactly what you have done above, just add `os.flush();` before `os.close();` – blgt Jun 27 '14 at 13:25
  • 1
    @blgt Close implies a flush. No problem there. – Durandal Jun 27 '14 at 14:25
  • @Durandal Huh. You're right; looking it up, `flush` is actually an empty method in this case, `write` makes the native call itself – blgt Jun 27 '14 at 14:52

1 Answers1

9

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!

Kaz Miller
  • 949
  • 3
  • 22
  • 40