2010-01-12 34 views
1

我正在使用Java AWT縮放JPEG圖像以創建縮略圖。當圖像具有正常採樣因子(2x2,1x1,1x1)時,代碼正常工作(2x2,1x1,1x1)如何在Java中使用非標準採樣因子來縮放JPEG圖像?

但是,具有此採樣因子(1x1,1x1,1x1)的圖像在縮放時會產生問題。雖然功能是可識別的,但顏色會損壞。

original和縮略圖: alt text http://otherplace.in/thumb1.jpg

我使用的代碼大致相當於:

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

(的this page代碼提供)

有沒有更好的辦法做到這個?

這是一個test image,採樣因子爲[1x1,1x1,1x1]。

+0

使用'ImageIO'到編碼*半透明*圖像爲JPEG時,我已經看到了這個效果,但我不認爲這也適用於你的例子作爲輸出圖像是不透明的('TYPE_INT_RGB'。)這是代碼樣品是否完整或者是否有其他後處理應用於圖像?有可能無意中產生半透明圖像(例如'AffineTransformOp'用'TYPE_BILINEAR'將在殼體中添加alpha通道到抗混疊所產生的圖像的邊緣不位於一個確切的像素邊界上。) – finnw 2010-05-12 12:41:31

回答

2

我相信問題不在於縮放,而是在構建BufferedImage時使用不兼容的顏色模型(「圖像類型」)。

在Java中創建體面的縮略圖非常困難。這是一個detailed discussion

+0

我已讀討論並正在使用其中一些技術來加快縮放。但似乎與我的問題無關。但是,不兼容的顏色模型在圖像加載階段是可能的嫌疑犯。我正在使用'javax.imageio.ImageIO.read'將圖像加載到內存中。也許它不支持異常採樣因素。 – HRJ 2010-01-12 15:21:56