Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating alpha images in java

Tags:

java

java-2d

I'm about to start work on a project which will generate some PNGs with alpha (gradients) and hoping to draw them programmatically within java.

For (a simple) example, I would like to draw a box, add a drop-shadow and then save this to a PNG file which can then be overlayed on some other graphic.

  1. Is this possible with the standard JRE system libraries?
  2. which libraries would make this kind of operation simple?

thanks.

like image 849
pstanton Avatar asked Aug 27 '26 01:08

pstanton


1 Answers

Is this possible with the standard JRE system libraries?

Yes, it is possible and is pretty simple aswell. The code below produces this image (transparent png):

screenshot

public static void main(String[] args) throws IOException {

    int x = 50, y = 50, w = 300, h = 200;

    // draw the "shadow"
    BufferedImage img = new BufferedImage(400, 300, BufferedImage.TYPE_INT_ARGB);
    Graphics g = img.getGraphics();
    g.setColor(Color.BLACK);
    g.fillRect(x + 10, y + 10, w, h);

    // blur the shadow
    BufferedImageOp op = getBlurredOp();
    img = op.filter(img, null);

    // draw the box
    g = img.getGraphics();
    g.setColor(Color.RED);
    g.fillRect(x, y, w, h);

    // write it to disk
    ImageIO.write(img, "png", new File("test.png"));
}

private static BufferedImageOp getBlurredOp() {

    float[] matrix = new float[400];
    for (int i = 0; i < 400; i++)
        matrix[i] = 1.0f/400.0f;

    return new ConvolveOp(new Kernel(20, 20, matrix),
                          ConvolveOp.EDGE_NO_OP, null);
}

Which libraries would make this kind of operation simple?

I would say that it depends on your other use cases. For simple shapes like boxes and ovals I would go for the solution above, no library is needed.

like image 121
dacwe Avatar answered Aug 29 '26 16:08

dacwe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!