Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize an image without loading into memory?

I'd like to check the dimensions of an image, and then size it down if the width exceeds a given threshold. When I load a 6MB JPEG image with ImageIO.read(), the BufferedImage allocates about 45MB of heap space. Is there a way to do a passthrough image resize without loading all the data into memory? I tried passing ImageIO.read() a File object, thinking it would stream the data from disk, but it doesn't help.

like image 884
Boris Burtin Avatar asked May 17 '11 00:05

Boris Burtin


3 Answers

Check out im4java and JMagick. Both use an extremely efficient external tool called ImageMagick for image manipulation. Im4Java calls the command-line app (does work in separate process), and JMagick calls it within the same process via JNI.

If I'm doing simple image manipulation (resizing, scaling, rotating, etc), I'd much rather let ImageMagick do it for me. It'll be faster, more reliable, and consume less memory than anything you'd implement in a similar amount of time.

Hope this helps!

like image 128
Ben Burns Avatar answered Nov 15 '22 11:11

Ben Burns


I've used jmagick before with excellent results, however it can be fiddly to get it working in different environments (sticking the jars in the right place, making sure you've got the correct build of imagemagick, etc).

You might want to consider using imgscalr (http://www.thebuzzmedia.com/software/imgscalr-java-image-scaling-library). It's an open source, pure java image manipulation library available under the Apache 2.0 license. Much much (much..) easier to use and faster than that horrendous Java2D stuff.

like image 24
rcgeorge23 Avatar answered Nov 15 '22 11:11

rcgeorge23


You can use ImageInfo to check the width and height of the image without loading it into memory. I do not know of a library that will allow you to re-size without loading the image in memory. 45MB is not all that much memory really. Can you just increase your heap size?

like image 38
dennisjtaylor Avatar answered Nov 15 '22 09:11

dennisjtaylor