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.
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.
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.
Just do: Image newImage = yourImage. getScaledInstance(newWidth, newHeight, Image. SCALE_DEFAULT);
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With