Question

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;
}
Was it helpful?

Solution

You are always using the same scaling factor for the x- and the y-direction.

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;
}    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top