繁体   English   中英

使用Java缩放图像会产生空白

[英]Scaling Image with Java produces black space

我编写了以下功能来按比例缩小图像。 但是,在进行缩放时,生成的图像始终是正方形图像,并且在图像的底部或右侧具有黑色空间。 我在这里做错了什么?

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;
}

您始终在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;
}    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM