How to scale a BufferedImage in java

How to scale a BufferedImage in java

You can scale a BufferedImage in Java using the AffineTransformOp class from the java.awt.image package. Here's an example of how to scale a BufferedImage:

import javax.imageio.ImageIO; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class ImageScaler { public static void main(String[] args) { try { // Load the original image BufferedImage originalImage = ImageIO.read(new File("original.jpg")); // Specify the scaling factor (e.g., 0.5 for 50% reduction) double scale = 0.5; // Calculate the new dimensions int newWidth = (int) (originalImage.getWidth() * scale); int newHeight = (int) (originalImage.getHeight() * scale); // Create a scaled BufferedImage with the new dimensions BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB); // Get the graphics context of the scaled image Graphics2D g2d = scaledImage.createGraphics(); // Set rendering hints for better quality (optional) g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Create an AffineTransform for scaling AffineTransform at = AffineTransform.getScaleInstance(scale, scale); // Apply the transformation to the image AffineTransformOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); op.filter(originalImage, scaledImage); // Dispose of the graphics context g2d.dispose(); // Save the scaled image ImageIO.write(scaledImage, "PNG", new File("scaled.png")); System.out.println("Image scaled successfully."); } catch (IOException e) { e.printStackTrace(); } } } 

In this example:

  1. Load the original image using ImageIO.read().
  2. Specify the scaling factor you want. For example, a scale value of 0.5 will reduce the image to 50% of its original size.
  3. Calculate the new dimensions of the scaled image.
  4. Create a new BufferedImage with the specified dimensions.
  5. Get the graphics context of the scaled image and set rendering hints for better quality (optional).
  6. Create an AffineTransform to specify the scaling transformation.
  7. Apply the transformation to the original image using AffineTransformOp.
  8. Dispose of the graphics context.
  9. Save the scaled image using ImageIO.write().

Make sure to replace "original.jpg" with the path to your own input image and "scaled.png" with the desired output file name and format.


More Tags

rubygems pgp object big-o svg-sprite pyqtgraph browser-automation avplayer celery nightwatch.js

More Java Questions

More Biochemistry Calculators

More General chemistry Calculators

More Everyday Utility Calculators

More Retirement Calculators