I am trying to resized a bufferedimage. I am able to store it and show up on a jframe no problems but I can't seem to resize it. Any tips on how I can change this to make it work and show the image as a 200*200 file would be great
private void profPic(){
String path = factory.getString("bottle");
BufferedImage img = ImageIO.read(new File(path));
}
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
int w = img.getWidth();
int h = img.getHeight();
BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
Graphics2D g = dimg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
g.dispose();
return dimg;
}
Check this out, it helps:
If all that is required is to resize a
BufferedImage
in theresize
method, then the Thumbnailator library can do that fairly easily:The above code will resize the
img
to fit the dimensions ofnewW
andnewH
while maintaining the aspect ratio of the original image.If maintaining the aspect ratio is not required and resizing to exactly the given dimensions is required, then the
forceSize
method can be used in place of thesize
method:Using the
Image.getScaledInstance
method will not guarantee that the aspect ratio of the original image will be maintained for the resized image, and furthermore, it is in general very slow.Thumbnailator uses a technique to progressively resize the image which can be several times faster than
Image.getScaledInstance
while achieving an image quality which generally is comparable.Disclaimer: I am the maintainer of this library.
Updated answer
I cannot recall why my original answer worked but having tested it in a separate environment, I agree, the original accepted answer doesn't work (why I said it did I cannot remember either). This, on the other hand, did work:
Here's some code that I have used to resize bufferedimages, no frills, pretty quick:
This is a shortened version of what is actually happening in imgscalr, if you just want to use the "balanced" smoothing:
try the imgscalr library. Best lib i found- very fast, good quality and simple to use
http://www.thebuzzmedia.com/software/imgscalr-java-image-scaling-library/