Generating alpha images in java
I am about to start a project that will generate some PNGs with alpha (gradients) and hope to make them programmatically in java.
For a (simple) example, I would like to draw a window, add a shadow and save it as a PNG file, which can then be overlaid on some other graphics file.
- Is this possible with the JRE standard system libraries?
- what libraries would make this kind of work easier?
thank.
+3
source to share
1 answer
Is this possible with the JRE standard system libraries?
Yes, it is possible and quite simple. The code below creates this image (transparent png):
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);
}
What libraries would make this kind of work easier?
I would say it depends on your other use cases. For simple shapes like boxes and ovals I would go for the solution above, no library needed.
+5
source to share