I'm having a problem with image scaling. When I use the following code to scale an image it ends up with a line either at the bottom or on the right side of the image.
double scale = 1;
if (scaleHeight >= scaleWidth) {
scale = scaleWidth;
} else {
scale = scaleHeight;
}
AffineTransform af = new AffineTransform();
af.scale(scale, scale);
AffineTransformOp operation = new AffineTransformOp(af, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
BufferedImage bufferedThumb = operation.filter(img, null);
The original image
The scaled image
Does anyone know why the line appears?
Thanks!
EDIT:
Added the complete method code:
public static final int SPINNER_MAX_WIDTH = 105;
public static final int SPINNER_MAX_HEIGHT = 70;
public void scaleImage(BufferedImage img, int maxWidth, int maxHeight, String fileName) {
double scaleWidth = 1;
double scaleHeight = 1;
if (maxHeight != NOT_SET) {
if (img.getHeight() > maxHeight) {
scaleHeight = (double) maxHeight / (double) img.getHeight();
}
}
if (maxWidth != NOT_SET) {
if (img.getWidth() > maxWidth) {
scaleWidth = (double) maxWidth / (double) img.getWidth();
}
}
double scale = 1;
if (scaleHeight >= scaleWidth) {
scale = scaleWidth;
} else {
scale = scaleHeight;
}
AffineTransform af = new AffineTransform();
af.scale(scale, scale);
AffineTransformOp operation = new AffineTransformOp(af, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
BufferedImage bufferedThumb = operation.filter(img, null);
if (bufferedThumb != null) {
File imageFile = new File(fileName);
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
try {
ImageIO.write(bufferedThumb, fileType, imageFile);
} catch (IOException e) {
logger.error("F开发者_JAVA技巧ailed to save scaled image: " + fileName + "\n" + e.getMessage());
}
}
}
The maxWidth and maxHeight parameters in the method call is set to the SPINNER_MAX_* constants.
Thanks!
Can you give us the rest of the code - how you manipulate the bufferedThumb
, because if you just save it to to a file it should be fine.
ImageIO.write(bufferedThumb, "PNG", new File("img.png"));
What java version do you use?
EDITED:
What you can try is to construct the final image explicitly like this:
BufferedImage bufferedThumb = new BufferedImage(maxWidth, maxHeight, BufferedImage.TYPE_INT_ARGB);
operation.filter(img, bufferedThumb);
to make sure what color mode is being used.
I think your issue may be related to this bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6725106
Another thing is to maybe use a differnt interpolation type like:
AffineTransformOp.TYPE_BILINEAR
For more information have a look at: http://www.dpreview.com/learn/?/key=interpolation
精彩评论