Scale image in Java and preserve its quality
There are many ways to scale/resize images in Java, but it could be very tricky to make some of them produce satisfying output in terms of image quality and also, processing time. There are core Java approaches to this issue, but third-party libraries offer more optimization in the background so that we can scale an image without any specific additional configuration and get a satisfying result. In this article, we’ll show you the easiest ways to scale, and still, keep image quality.
From the core Java features, there are two main ways to scale image — using Graphics2D and Image.getScaledInstance(). They provide us with certain configuration options called «hints» that can help us balance between processing time and output image quality. They’re not in the scope of this article.
From third-party libraries, we chose ImageScalr and Thumbnailator as libraries that would pick the best possible algorithm for you, based on input parameters — current image and target width/height. We tried both of them and the result was very good, comparing to core Java features where you have to tweak, but still not get what you want. Both of them support all file types that are supported by ImageIO.
Scale image using Thumbnailator
First, we need to add Maven dependency for this one:
net.coobird thumbnailator 0.4.11
This code sample shows how to scale image using Thumbnailator:
public class ThumbnailatorScaleExample < static BufferedImage scaleImage(BufferedImage originalImage, int targetWidth, int targetHeight) throws Exception < ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); Thumbnails.of(originalImage) .size(targetWidth, targetHeight) .outputFormat("JPEG") .outputQuality(0.99) .toOutputStream(byteOutputStream); byte[] data = byteOutputStream.toByteArray(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data); return ImageIO.read(byteArrayInputStream); >public static void main(String[] args) throws Exception < BufferedImage originalImage = ImageIO.read(new File("path/to/your/input/file.jpg")); BufferedImage outputImage = resizeImage(originalImage, 300, 300); ImageIO.write(outputImage, "jpg", new File("path/to/your/output/file.jpg")); >>
Scale image using ImgScalr
The Maven dependency for ImgScalr:
org.imgscalr imgscalr-lib 4.2
This code sample shows how to scale image using ImgScalr library:
public class ImagescalrScaleExample < static BufferedImage scaleImage(BufferedImage originalImage, int targetWidth) throws Exception < return Scalr.resize(originalImage, targetWidth); >public static void main(String[] args) throws Exception < BufferedImage originalImage = ImageIO.read(new File("path/to/your/input/image.jpg")); BufferedImage outputImage = scaleImage(originalImage, 300, 300); ImageIO.write(outputImage, "jpg", new File("path/to/your/output/image.jpg")); >>
Check also.
Image Scaling With imgscalr – Java Image Scaling Library
imgscalr is a simple and efficient image scaling library implemented purely in java and provides a handful of operations for image manipulation. This library can be useful in creating thumbnail or preview images of various sizes from larger uploaded images or performing basic image manipulation operation, incuding scaling, cropping, rotation etc. imagescalr is a set of most commonly used operations optimized for better performance & speed and is not meant to be a full-scale Java graphics library like JAI.
Installation:
If you are using grails then you can use it simply by adding following dependency to your BuildConfig.groovy file dependencies section:
[code language=”groovy”]compile "org.imgscalr:imgscalr-lib:4.2" //adjust version according to your need
[/code]
and if you are using maven then add the following dependency to pom.xml:
In its simplest form you can resize image by passing just two arguments: your image (BufferedImage) and target size (in pixels).
[code language=”groovy”]BufferedImage scaledImage = Scalr.resize(image, 250)
[/code]
Here, we are resizing our image (maintaining its original proportion) to a width and height no bigger than target size.
If you wanted finer grained control over image scaling, its quality and a light anti-aliasing filter to it then your method call will look something like this:
[code language=”groovy”]BufferedImage scaledImage = Scalr.resize(image, Scalr.Method.QUALITY, Scalr.Mode.FIT_TO_WIDTH, targetWidth, targetHeight, Scalr.OP_ANTIALIAS)
[/code]
Here, Scalr.Method.QUALITY indicates that the scaling implementation should do everything it can to create as nice of a result as possible, Scalr.Mode.FIT_TO_WIDTH indicates that the scaling implementation should calculate dimensions for the resultant image that best-fit within the given width, regardless of the orientation of the image and Scalr.OP_ANTIALIAS is a ConvolveOp using a very light “blur” kernel that acts like an anti-aliasing filter (softens the image a bit) when applied to an image.
Method and Mode are the enums defined on the Scalr class and are used in conjunction with all of the resize methods.
Given below is the code snippet in grails that you can use as a reference:
[code language=”groovy”]import org.imgscalr.Scalr
import javax.imageio.ImageIO
import java.awt.image.BufferedImage
def scaleImage() String pathToOriginalImage = "/home/tothenew/Desktop/image.jpg"
String imageFormat = "jpg"
Integer targetWidth = 400
Integer targetHeight = 600
File originalImageFile = new File(pathToOriginalImage)
BufferedImage image = ImageIO.read(originalImageFile)
BufferedImage scaledImg = Scalr.resize(image, Scalr.Method.QUALITY, Scalr.Mode.FIT_TO_WIDTH,
targetWidth, targetHeight, Scalr.OP_ANTIALIAS)
ByteArrayOutputStream baos = new ByteArrayOutputStream()
ImageIO.write(scaledImg, imageFormat, baos)
baos.flush()
byte[] scaledImageInByte = baos.toByteArray()
baos.close()
return scaledImageInByte
>
[/code]
If you want to dive into more depth, go to below url:
Java Scale Image File using Imgscalr
In this Java tutorial we learn how to scale an image file using the Scalr class of Imgscalr Java library.
How to add Imgscalr library to the Java project
To use the Imgscalr library in the Gradle build project, add the following dependency into the build.gradle file.
implementation 'org.imgscalr:imgscalr-lib:4.2'
To use the Imgscalr library in the Maven build project, add the following dependency into the pom.xml file.
org.imgscalr imgscalr-lib 4.2
To have more information about the Imgscalr library you can visit the project repository at github.com/rkalla/imgscalr
How to scale an image file in Java
The Imgscalr library provides the method Scalr.resize() to allow resizing a given image. By using this method we can scale an image file to a smaller or bigger version. The Java example code below to show you how to scale an image using the Scalr.resize() method.
import org.imgscalr.Scalr; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class ScaleImageExample public static void main(String. args) String originalFilePath = "D:\\TestData\\Albert_Einstein.jpg"; String scaleFilePath1 = "D:\\TestData\\Albert_Einstein_big.jpg"; String scaleFilePath2 = "D:\\TestData\\Albert_Einstein_small.jpg"; scaleImage(originalFilePath, scaleFilePath1, 5.5); scaleImage(originalFilePath, scaleFilePath2, 0.3); > public static void scaleImage(String originalFilePath, String scaleFilePath, double scaleRatio) try File sourceFile = new File(originalFilePath); BufferedImage originalImage = ImageIO.read(sourceFile); int width = (int)Math.ceil(originalImage.getWidth() * scaleRatio); int height = (int)Math.ceil(originalImage.getHeight() * scaleRatio); BufferedImage thumbnailImage = Scalr.resize(originalImage, Scalr.Method.ULTRA_QUALITY, width, height); File thumbnailFile = new File(scaleFilePath); ImageIO.write(thumbnailImage, "jpg", thumbnailFile); originalImage.flush(); thumbnailImage.flush(); > catch (IOException e) e.printStackTrace(); > > >