【发布时间】:2010-03-19 10:49:20
【问题描述】:
我遇到了图像缩放问题。当我使用以下代码缩放图像时,它会在图像底部或右侧出现一条线。
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);
原图
缩放后的图像
有人知道为什么会出现这条线吗?
谢谢!
编辑:
添加了完整的方法代码:
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("Failed to save scaled image: " + fileName + "\n" + e.getMessage());
}
}
}
方法调用中的 maxWidth 和 maxHeight 参数设置为 SPINNER_MAX_* 常量。
谢谢!
【问题讨论】:
-
我运行了您的代码(使用您的图像作为输入),它看起来不错。你用什么
scaleWidth/scaleHeight?你是如何加载图像的?你是如何显示/保存它的? -
我添加了完整的方法 - 谢谢。
标签: java image-processing java-2d affinetransform