views:

206

answers:

1

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 ].

+2  A: 

I believe the problem is not the scaling, but your use of an incompatible color model ("image type") when constructing your BufferedImage.

Creating decent thumbnails in Java is surprisingly hard. Here's a detailed discussion.

Jonathan Feinberg
I have read that discussion and am using some of those techniques for faster scaling. But doesn't seem relevant to my problem. But yes, incompatible color model is a possible suspect at image load stage. I am using `javax.imageio.ImageIO.read` for loading the image into memory. Perhaps it doesn't support abnormal sampling factors.
HRJ