我在图像缩放方面遇到问题。当我使用以下代码缩放图像时,它会在图像的底部或右侧以一条线结束。
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_* 常量。
谢谢!