我正在将签名图像保存为 .jpg 图片。我使用 graphic2d 在图像上绘制签名的每个像素(使用签名平板电脑获得)并且效果很好,但我总是得到白色背景。 如果我想在PDF文档上签名,jpg图像的白色方 block 的边框会覆盖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;
}
我试图将它设置为透明但没有成功,所以我发布了这个工作部分。
最佳答案
使用 BufferedImage.TYPE_INT_ARGB
而不是 BufferedImage.TYPE_INT_RGB
。并保存为PNG
图片,JPEG
不支持透明
更新:
要设置背景透明,使用它:
g2d.setComposite(AlphaComposite.Clear);
g2d.fillRect(0, 0, w, h);
然后绘制图像:
g2d.setComposite(AlphaComposite.Src);
drawPoints(Tablet.getPenPoints(), g2d, Color.BLACK);
关于java - 以透明背景保存缓冲图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17271812/