我遇到圖像縮放問題。當我使用下面的代碼來縮放圖像時,它會以圖像底部或右側的一條線結束。Java:使用AffineTransform縮放圖像時出現線條
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'?你如何加載圖像?你如何顯示/保存它? – Ash 2010-03-19 21:23:53
我添加了完整的方法 - 感謝。 – Malakim 2010-03-21 07:37:32