0

Im using this code in java:

    Image img = ImageIO.read(new File("imagepath/file.png").getScaledInstance(300, 300,        BufferedImage.SCALE_SMOOTH);

    BufferedImage buffered = new BufferedImage(300, 300, BufferedImage.SCALE_FAST);
    buffered.getGraphics().drawImage(img, 0, 0 , null);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageIO.write(buffered, "png", os); 
    InputStream in = new ByteArrayInputStream(os.toByteArray());
    return in;

This successfully scales down and shows a thumbnail in the browser using my laptop. However when I'm launch it on my mini server (Raspberry Pi) it is horrible slow. More accurate is about 4 times longer than loading the actual full-res image.

Can anybody tell me how this is even possible? 300x300 < 1280x720! Should be less work and less bandwidth!

Cheers!

Caresi
  • 59
  • 2
  • 11
  • 1
    are you saving the resized image somewhere? If not, you're basically redoing the resizing operation EVERY time the image is requested. and note that a 1280x720 .jpg image requires ~2.7 meg of ram to store in raw bitmap format in memory. a Pi is not exactly a speed-demon of a system. – Marc B Dec 16 '14 at 19:07
  • 1
    Because the Raspberry Pi has a much slower processor than your laptop, and resizing the image is a processor-intensive operation. – Jesper Dec 16 '14 at 19:08
  • @MarcB Wow 2.7MB!? Is it really that bad :S Is there any way to do it more seamless into a stream or is caching the way to go? – Caresi Dec 16 '14 at 19:11
  • 1280x720 = 921,600 pixels. 24bit image = 3 bytes/pixel, so 921,600 * 3 = ~2.65meg. – Marc B Dec 16 '14 at 19:11

1 Answers1

3

getScaledInstance is known to be slow, see for example this article for a detailed explanation.

Note that your

BufferedImage buffered = new BufferedImage(300, 300, BufferedImage.SCALE_FAST);

line is wrong, here for the third argument you should specify the image type ( TYPE_INT_RGB, TYPE_INT_ARGB, TYPE_INT_ARGB_PRE etc) and not SCALE_FAST (which is not even a field in BufferedImage)

Also see this: How to scale a BufferedImage

For quality downscaling see this: Quality of Image after resize very low -- Java

Community
  • 1
  • 1
lbalazscs
  • 17,474
  • 7
  • 42
  • 50
  • Thank you! Weird that the code worked before and didn't crash. guess that it used some default value because the one I sent in was completely wrong. – Caresi Dec 16 '14 at 19:16
  • Fyi- one step scaling generally doesn't produce a nice result (especially over a large range), typically better to use a stepped approach, [for example](http://stackoverflow.com/questions/14115950/quality-of-image-after-resize-very-low-java/14116752#14116752) – MadProgrammer Dec 16 '14 at 20:01
  • @MadProgrammer yes, and this is actually also discussed in detail in the "The Perils of Image.getScaledInstance()" article (in the "On-the-Fly Scaling" part), but for completeness I also included your link in the answer – lbalazscs Dec 16 '14 at 20:13