Save buffered image with transparent background
Asked Answered
P

5

18

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.

Psychopathology answered 24/6, 2013 at 9:9 Comment(1)
#58675950Markhor
A
56

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);
Azriel answered 24/6, 2013 at 9:16 Comment(2)
I used BufferedImage.TYPE_INT_ARGB, and I saved it as a png image. But now how can I set the alpha paramether of the background?Psychopathology
Excellent solution :)M16
I
2

ready to use end to end example

it will create png picture with transparency and 2 x rectangles

compilation time - 2019_04_10__00_12_03_236

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

// ready to use end to end example
// it will create png picture with transparency and 2 x rectangles
// compilation time - 2019_04_10__00_12_03_236
public class java_create_png_image_with_transparency_end_to_end_example {

    public static void main(String[] args) throws IOException {
        Path outPath = Paths.get("C:\\_tmp_out_\\");
        if (!Files.exists(outPath)) {
            Files.createDirectory(outPath);
        }

        String timeNow = DateTimeFormatter
                .ofPattern("yyyy_MM_dd__HH_mm_ss_SSS")
                .format(LocalDateTime.now());
        String filename = "test_png_pic__" + timeNow + "__.png";
        File absOutFile = outPath.resolve(filename).toFile();

        int width = 300;
        int height = 300;

        BufferedImage bufferedImage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = bufferedImage.createGraphics();
        g2d.setComposite(AlphaComposite.Clear);
        g2d.fillRect(0, 0, width, height);

        g2d.setComposite(AlphaComposite.Src);
        int alpha = 127; // 50% transparent
        g2d.setColor(new Color(255, 100, 100, alpha));
        g2d.fillRect(100, 100, 123, 123);

        g2d.setColor(new Color(0, 0, 0));
        g2d.fillRect(30, 30, 60, 60);

        g2d.dispose();

        ImageIO.write(bufferedImage, "png", absOutFile);
        System.out.println("File saved to:");
        System.out.println(absOutFile);
    }
}
Iy answered 10/4, 2019 at 11:16 Comment(0)
F
1

You are setting the Buffered Image have a type of just RGB which has no Alpha component, you will have to use one that does have alpha to maintain transparency.

Fortyniner answered 24/6, 2013 at 9:14 Comment(0)
L
1

As others have mentioned, you can't save JPEGs with transparency.

However, it's possible to store your file as you do (in JPEG, although I suggest using a grayscale JPEG in this case) and later interpret the white parts as transparent, and the black parts as non-transparent (ie: use the grayscale image as an alpha-mask). Then you could simply color the non-transparent parts either black or blue, to look like pen-ink.

Think of the white area as the paper, and the black parts as covered by ink. Note that this technique will only work for the use case where all white pixels should be transparent. Other answers in this thread will work better in the general case.

Looney answered 24/6, 2013 at 9:18 Comment(2)
And if an image has the white parts inside it which should not be transparent?Azriel
@Azriel The OP's question was about signatures from a tablet, so I don't think it matters. Think of the white area as the paper, and the black parts as covered by ink. If you really want non-transparent white parts, it will not work.Looney
C
0

JPEG does not support transperency. You have to use a different target format like png for example.

Confucian answered 24/6, 2013 at 9:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.