簡體   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