[英]Scaling Image with Java produces black space
I have written the following function to scale down images. 我编写了以下功能来按比例缩小图像。 But while the scaling works, the produced images are always square images and have a black space at the bottom or right side of the image. 但是,在进行缩放时,生成的图像始终是正方形图像,并且在图像的底部或右侧具有黑色空间。 What I am doing wrong here? 我在这里做错了什么?
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;
}
You are always using the same scaling factor for the x- and the y-direction. 您始终在x方向和y方向上使用相同的比例因子。
Although you could fix this by specifying two scaling factors like this 尽管您可以通过指定两个比例因子来解决此问题
double scaleX = (double) width / srcWidth;
double scaleY = (double) height / srcHeight;
AffineTransform at = new AffineTransform();
at.scale(scaleX, scaleY);
I wonder why you are doing is this way. 我不知道你为什么这样做。 Just creating a scaled version of an image is usually rather easy...: 仅创建图像的缩放版本通常很容易...:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.