2013-09-28 98 views
1

下面的代碼調整圖像大小。不幸的是,垂直圖像的圖像在邊上有黑條。它看起來好像透明的或空白的空間充滿了黑色。我試着將背景顏色設置爲白色,並使用alphaRGB,但似乎無法動搖它。無法調整圖像大小並保持透明度

OrderProductAssetEntity orderProductAssetEntity = productAssets.get(jobUnitEntity.getId()); 
    File asset = OrderProductAssetService.getAssetFile(orderProductAssetEntity); 
    if (asset.exists()) { 
     //resize the asset to a smaller size 
     BufferedImage resizedImage = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB); 
     Graphics2D g = resizedImage.createGraphics(); 
     g.setBackground(Color.WHITE); 
     g.drawImage(ImageIO.read(asset), 0, 0, width, height, null); 
     g.dispose(); 

     jobUnitImages.put(orderProductAssetEntity.getOriginalLocation(), new PDJpeg(document, resizedImage)); 
    } else { 
     jobUnitImages.put(orderProductAssetEntity.getOriginalLocation(), null); 
    } 

回答

2

首先,如果你需要透明度,BufferedImage.TYPE_INT_RGB將無法​​正常工作,你需要BufferedImage.TYPE_INT_ARGB。不知道你是否已經嘗試過,只想清楚。

其次,這條線:

g.setBackground(Color.WHITE); 

...沒有隻設置圖形上下文的當前背景色。它確實而不是用該顏色填充背景。爲此,您還需要執行g.clearRect(0, 0, width, height)。但我通常寧願使用g.setColor(...)g.fillRect(...)來代替以避免混淆。

或者,如果你喜歡,你還可以使用drawImage方法,它接受Color像這樣的倒數第二個參數:

g.drawImage(image, 0, 0, width, height, Color.WHITE, null); 

編輯:

三,類名PDJpeg意味着該圖像稍後將存儲爲JPEG,因此您可能會失去透明度。所以最好的可能是堅持TYPE_INT_RGB,並用正確的顏色填充背景(並以正確的方式進行;-)。

+0

完美!我用'g.drawImage(...)'謝謝! – Webnet

相關問題