【发布时间】:2014-03-29 21:21:16
【问题描述】:
我编写了以下函数来缩小图像。但是,虽然缩放有效,但生成的图像始终是方形图像,并且在图像的底部或右侧有一个黑色空间。我在这里做错了什么?
private BufferedImage scaleImageTo(BufferedImage image, int width, int height) throws Exception {
// Fetch the width and height of the source image, ...
int srcWidth = image.getWidth();
int srcHeight = image.getHeight();
// ... verify that it is larger than the target image ...
if (srcWidth < width && srcHeight < height) {
throw new Exception();
}
// ... and setup the target image with the same dimensions.
BufferedImage scaledImage;
if (image.getType() == BufferedImage.TYPE_CUSTOM) {
scaledImage = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
} else {
scaledImage = new BufferedImage(width, height, image.getType());
}
// Calculate the scale parameter.
double scale = 1;
if (srcWidth - width >= srcHeight - height) {
scale = ((double) width) / srcWidth;
} else {
scale = ((double) height) / srcHeight;
}
// Setup the scaling transformation ...
AffineTransform at = new AffineTransform();
at.scale(scale, scale);
// ... and the transformation interpolation type.
AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
// Generate the scaled image ...
scaledImage = scaleOp.filter(image, scaledImage);
// ... and return it.
return scaledImage;
}
【问题讨论】:
标签: java image scaling bufferedimage