Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I scale a BufferedImage

I have viewed this question, but it does not seem to actually answer the question that I have. I have a, image file, that may be any resolution. I need to load that image into a BufferedImage Object at a specific resolution (say, for this example, 800x800). I know the Image class can use getScaledInstance() to scale the image to a new size, but I then cannot figure out how to get it back to a BufferedImage. Is there a simple way to scale a Buffered Image to a specific size?

NOTE I I do not want to scale the image by a specific factor, I want to take an image and make is a specific size.

like image 773
ewok Avatar asked Jul 06 '12 17:07

ewok


People also ask

How do I find the size of a BufferedImage?

Before you load the image file as a BufferedImage make a reference to the image file via the File object. File imgObj = new File("your Image file path"); int imgLength = (int) imgObj. length(); imgLength would be your approximate image size though it my vary after resizing and then any operations you perform on it.

How do you scale an image in Java?

The simplest way to scale an image in Java is to use the AffineTransformOp class. You can load an image into Java as a BufferedImage and then apply the scaling operation to generate a new BufferedImage. You can use Java's ImageIO or a third-party image library such as JDeli to load and save the image.

How do you scale an image in Java Swing?

Just do: Image newImage = yourImage. getScaledInstance(newWidth, newHeight, Image. SCALE_DEFAULT);

What is the difference between BufferedImage and image?

List, the difference between Image and BufferedImage is the same as the difference between List and LinkedList. Image is a generic concept and BufferedImage is the concrete implementation of the generic concept; kind of like BMW is a make of a Car. Show activity on this post. Image is an abstract class.


1 Answers

Something like this? :

 /**
 * Resizes an image using a Graphics2D object backed by a BufferedImage.
 * @param srcImg - source image to scale
 * @param w - desired width
 * @param h - desired height
 * @return - the new resized image
 */
private BufferedImage getScaledImage(Image srcImg, int w, int h){
    BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TRANSLUCENT);
    Graphics2D g2 = resizedImg.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(srcImg, 0, 0, w, h, null);
    g2.dispose();
    return resizedImg;
}
like image 167
alain.janinm Avatar answered Sep 20 '22 21:09

alain.janinm