Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save buffered image with transparent background

I'm saving the image of a signature as a .jpg picture. I use graphic2d to paint on the image every pixel of the signature (gotten with a signature tablet) and it works perfectly but I'm always gettin a white background. If I want to put the signature on a PDF document, the borders of the white square of the jpg image covers some of the words of the PDF.

What I want to get is to save the jpg image with a transparent background, so when I put it on the PDF there are no words covered with the white image background but just the signature lines.

This is the code that saves the buffered image. It does it with the white background.

 // 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;
}

I tried to set it transparent but with no success, so I posted this working part.

like image 783
Igr Avatar asked Jun 24 '13 09:06

Igr


People also ask

Can you save an image with a transparent background?

If you want to save your new image with its transparent background, choose either TIFF, PNG, or GIF formats. These formats support image transparency.

How do I save a JPEG with a transparent background?

Add a transparent area to a pictureClick Picture Tools > Recolor > Set Transparent Color. In the picture, click the color you want to make transparent.

How do I save a PNG with a transparent background?

Save As A Transparent PNG ImageClick “File” -> “Save As”. Select “PNG (*. PNG) as the file format. Note that though a transparent background looks checkered in Photoshop, it will actually be transparent in the final PNG file.

Can JPEG preserve transparency?

The JPEG format doesn't support transparency. But we can create our own transparency using a second image as an alpha channel.


1 Answers

Use BufferedImage.TYPE_INT_ARGB instead of BufferedImage.TYPE_INT_RGB. And save it to PNG image, JPEG does not support the transparency.

UPD:

For set the background transparent, use it:

g2d.setComposite(AlphaComposite.Clear);
g2d.fillRect(0, 0, w, h);

And for draw your image:

g2d.setComposite(AlphaComposite.Src);
drawPoints(Tablet.getPenPoints(), g2d, Color.BLACK);
like image 84
SeniorJD Avatar answered Oct 18 '22 20:10

SeniorJD