我写了以下功能来缩小图像。但是当缩放工作时,产生的图像总是方形图像并且在图像的底部或右侧具有黑色空间。我在这里做错了什么?
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;
}
答案 0 :(得分:0)
您始终对x方向和y方向使用相同的缩放系数。
虽然你可以通过指定两个这样的缩放因子来解决这个问题
double scaleX = (double) width / srcWidth;
double scaleY = (double) height / srcHeight;
AffineTransform at = new AffineTransform();
at.scale(scaleX, scaleY);
我想知道你为什么这样做。只是创建图像的缩放版本通常很容易......:
private static BufferedImage scaleImageTo(
BufferedImage image, int width, int height)
{
BufferedImage scaledImage =
new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = scaledImage.createGraphics();
g.setRenderingHint(
RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(image, 0, 0, width, height, null);
g.dispose();
return scaledImage;
}