How to scale JPEG images with a non-standard sampling factor in Java?

Posted by HRJ on Stack Overflow See other posts from Stack Overflow or by HRJ
Published on 2010-01-12T14:43:58Z Indexed on 2010/05/08 9:08 UTC
Read the original article Hit count: 241

I am using Java AWT for scaling a JPEG image, to create thumbnails. The code works fine when the image has a normal sampling factor ( 2x2,1x1,1x1 )

However, an image which has this sampling factor ( 1x1, 1x1, 1x1 ) creates problem when scaled. The colors get corrupted though the features are recognizable.

The original and the thumbnail: alt text

The code I am using is roughly equivalent to:

static BufferedImage awtScaleImage(BufferedImage image,
                                   int maxSize, int hint) {
    // We use AWT Image scaling because it has far superior quality
    // compared to JAI scaling.  It also performs better (speed)!
    System.out.println("AWT Scaling image to: " + maxSize);
    int w = image.getWidth();
    int h = image.getHeight();
    float scaleFactor = 1.0f;
    if (w > h)
        scaleFactor = ((float) maxSize / (float) w);
    else
        scaleFactor = ((float) maxSize / (float) h);
    w = (int)(w * scaleFactor);
    h = (int)(h * scaleFactor);
    // since this code can run both headless and in a graphics context
    // we will just create a standard rgb image here and take the
    // performance hit in a non-compatible image format if any
    Image i = image.getScaledInstance(w, h, hint);
    image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = image.createGraphics();
    g.drawImage(i, null, null);
    g.dispose();
    i.flush();
    return image;
}

(Code courtesy of this page )

Is there a better way to do this?

Here's a test image with sampling factor of [ 1x1, 1x1, 1x1 ].

© Stack Overflow or respective owner

Related posts about jpeg

Related posts about java