2010-03-19 32 views
2

我遇到圖像縮放問題。當我使用下面的代碼來縮放圖像時,它會以圖像底部或右側的一條線結束。Java:使用AffineTransform縮放圖像時出現線條

double scale = 1; 
if (scaleHeight >= scaleWidth) { 
    scale = scaleWidth; 
} else { 
    scale = scaleHeight; 
} 
AffineTransform af = new AffineTransform(); 
af.scale(scale, scale); 

AffineTransformOp operation = new AffineTransformOp(af, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); 
BufferedImage bufferedThumb = operation.filter(img, null); 

原始圖像

enter image description here

縮放後的圖像

enter image description here

有誰知道爲什麼線出現?

謝謝!

編輯:

添加了完整的方法代碼:

public static final int SPINNER_MAX_WIDTH = 105; 
public static final int SPINNER_MAX_HEIGHT = 70; 

public void scaleImage(BufferedImage img, int maxWidth, int maxHeight, String fileName) { 
    double scaleWidth = 1; 
    double scaleHeight = 1; 

    if (maxHeight != NOT_SET) { 
     if (img.getHeight() > maxHeight) { 
      scaleHeight = (double) maxHeight/(double) img.getHeight(); 
     } 
    } 

    if (maxWidth != NOT_SET) { 
     if (img.getWidth() > maxWidth) { 
      scaleWidth = (double) maxWidth/(double) img.getWidth(); 
     } 
    } 

    double scale = 1; 

    if (scaleHeight >= scaleWidth) { 
     scale = scaleWidth; 
    } else { 
     scale = scaleHeight; 
    } 

    AffineTransform af = new AffineTransform(); 
    af.scale(scale, scale); 

    AffineTransformOp operation = new AffineTransformOp(af, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); 
    BufferedImage bufferedThumb = operation.filter(img, null); 

    if (bufferedThumb != null) { 
     File imageFile = new File(fileName); 
     String fileType = fileName.substring(fileName.lastIndexOf(".") + 1); 
     try { 
      ImageIO.write(bufferedThumb, fileType, imageFile); 
     } catch (IOException e) { 
      logger.error("Failed to save scaled image: " + fileName + "\n" + e.getMessage()); 
     } 
    } 
} 

在方法調用的maxWidth和maxHeight參數設置爲SPINNER_MAX_ *常量。

謝謝!

+0

我跑你的代碼(使用作爲輸入圖像),它看起來很好。你在用什麼'scaleWidth' /'scaleHeight'?你如何加載圖像?你如何顯示/保存它? – Ash 2010-03-19 21:23:53

+0

我添加了完整的方法 - 感謝。 – Malakim 2010-03-21 07:37:32

回答

1

,你能不能給我們的代碼的其餘部分 - 你如何操縱bufferedThumb,因爲如果你只是把它保存到一個文件應該被罰款。

ImageIO.write(bufferedThumb, "PNG", new File("img.png")); 

你用什麼java版本?

編輯:

什麼,你可以嘗試是明確構成最終的圖像是這樣的:

BufferedImage bufferedThumb = new BufferedImage(maxWidth, maxHeight, BufferedImage.TYPE_INT_ARGB); 
operation.filter(img, bufferedThumb); 

,以確保正在使用的色彩模式。

我覺得你的問題可能與此錯誤: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6725106

的另一件事是可能使用不同的充插值類型,如:

AffineTransformOp.TYPE_BILINEAR 

欲瞭解更多信息,看看: http://www.dpreview.com/learn/?/key=interpolation

+0

添加了完整的方法 - 我使用JDK 1.6.0_18。 謝謝。 – Malakim 2010-03-21 07:37:14

+0

這可能是它,我會嘗試你的建議,看看他們解決問題。 謝謝! – Malakim 2010-03-23 07:11:05