代码之家  ›  专栏  ›  技术社区  ›  Ben

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

  •  2
  • Ben  · 技术社区  · 12 年前

    下面的代码调整图像的大小。不幸的是,作为垂直图像的图像的侧面有黑色条。看起来好像透明或空白的空间被黑色填满了。我试着将背景颜色设置为白色,并使用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 回复  |  直到 12 年前
        1
  •  3
  •   Harald K    12 年前

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