无法调整图像大小并保持透明度

时间:2013-09-28 02:12:50

标签: java image-processing

以下代码调整图像大小。不幸的是,作为垂直图像的图像在侧面具有黑条。看起来好像透明或空白区域充满了黑色。我已经尝试将背景颜色设置为白色,并使用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);
    }

1 个答案:

答案 0 :(得分:3)

首先,如果您需要透明度,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,并用正确的颜色填充背景(并以正确的方式进行; - )。

相关问题