Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize the original image into a common size of image in Java?

Tags:

java

image

resize

In Java, how can I resize an image into a default size for any kind or size of image?

like image 282
Venkat Avatar asked Feb 21 '10 11:02

Venkat


2 Answers

There are full articles on how to do this around the net, something like these should get you going:

  • Ultimate Java Image Manipulation (Includes many other image functions)
like image 27
Nick Craver Avatar answered Nov 08 '22 23:11

Nick Craver


You can't easily resize an image from one file size to another, BUT, most JPG/PNG/GIF/etc. tend to have similar file-sizes based on their resolutions. For example, a 200kb compressed JPG might typically be say 1280x960 in size. If that is the case, you would just target all your resize operations to size the target images to that size and get roughly the size constraint you want.

One really easy way to do this is to use very simple java image resizing library (Apache 2 license) that just does everything right for you. Example code to resize would look like this:

BufferedImage img = ImageIO.read(...); // load image
BufferedImage scaledImg = Scalr.resize(img, 1280, 960);

Your image proportions are honored, the library makes a best-guess at the method it should use based on the amount of change in the image due to scaling (FASTEST, BALANCED or QUALITY) and the best supported Java2D image types are always used to do the scaling to avoid the issue of "black" results or really terrible looking output (e.g. overly dithered GIF images).

Also, if you want to force it to output the best looking result possible in Java, the API call would look like this:

BufferedImage img = ImageIO.read(...); // load image
BufferedImage scaledImg = Scalr.resize(img, Method.QUALITY, 1280, 960);

The library use the Java2D recommended incremental scaling for you to give you the best looking result.

You can read through all the comments in the library (the code itself is doc'ed heavily) to see all the different JDK bugs that are worked around or optimizations that are made to improve the performance or memory usage. I spent a LOT of time tuning this implementation and have had a lot of good feedback from folks deploying it in web apps and other Java projects.

like image 55
Riyad Kalla Avatar answered Nov 09 '22 01:11

Riyad Kalla