使用透明背景保存缓冲图像

Igr*_*Igr 15 java graphics bufferedimage background transparent

我将签名图像保存为.jpg图片.我使用graphic2d在图像上绘制每个像素的签名(用签名平板电脑获得)并且它完美地工作但我总是得到白色背景.如果我想将签名放在PDF文档上,jpg图像的白色方块的边框覆盖了PDF的一些单词.

我想要的是用透明背景保存jpg图像,所以当我把它放在PDF上时,没有白色图像背景覆盖的文字,只有标记线.

这是保存缓冲图像的代码.它用白色背景做到了.

 // This method refers to the signature image to save
private RenderedImage getImage() {

    int width = tabletWidth;
    int height = tabletHeight;

    // Create a buffered image in which to draw
    BufferedImage bufferedImage = new BufferedImage(width, height,
            BufferedImage.TYPE_INT_RGB);

    // Create a graphics contents on the buffered image
    Graphics2D g2d = bufferedImage.createGraphics();

    // Draw graphics
    g2d.setColor(Color.WHITE);
    g2d.fillRect(0, 0, width, height);

    drawPoints(Tablet.getPenPoints(), g2d, Color.BLACK);

    // Graphics context no longer needed so dispose it
    g2d.dispose();

    return bufferedImage;
}
Run Code Online (Sandbox Code Playgroud)

我试图将它设置为透明但没有成功,所以我发布了这个工作部分.

Sen*_*rJD 48

BufferedImage.TYPE_INT_ARGB而不是BufferedImage.TYPE_INT_RGB.并将其保存为PNG图像,JPEG不支持透明度.

UPD:

要将背景设置为透明,请使用它:

g2d.setComposite(AlphaComposite.Clear);
g2d.fillRect(0, 0, w, h);
Run Code Online (Sandbox Code Playgroud)

并绘制你的形象:

g2d.setComposite(AlphaComposite.Src);
drawPoints(Tablet.getPenPoints(), g2d, Color.BLACK);
Run Code Online (Sandbox Code Playgroud)