Tags: applet, basic, class, complete, creating, experience, file, graphics2d, image, java, map, saving, scroll, steps, zoom
Basic steps for creating and saving an image as a file
On Java Studio » Java Knowledge
3,873 words with 2 Comments; publish: Sun, 23 Sep 2007 20:45:00 GMT; (15062.50, « »)
I have a good deal of experience with the Applet and Graphics2D class, having made a complete zoom/scroll map with it, but now I need to make some transparent png's with Java, and I've spent a lot of time looking both on Google and in these forums and I can't find any straightforward explanation of how to do it. All I want to do is:
-Create an empty, transparent image
-Draw some lines on it at angles which will make portions of it need to have alpha-level transparency
-Save it as a png
I would do this myself in Photshop, but I need it done precisely and several hundred times. Like I said, I know how to draw to a Graphics2D object, and I know about the paint method in the Applet class. However, I can't seem to figure out how to actually save an image file (especially a PNG), without doing some really convoluted and seemingly unecessary stuff with the Frame class and a bunch of other things. Can anyone help me, or direct me to the place that probably has already answered this?
http://java-knowledge.developerfaqs.com/q_java-tech_7934.html
All Comments
Leave a comment...
- 2 Comments

Creating an image with an alpha channel is easy: use BufferedImage's
constructor:BufferedImage(int width, int height, int type)
and pass it a type like TYPE_INT_ARGB. To write an image, use the class
ImageIO from javax.imagio. Demo:
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
public class Satanic {
public static void main(String[] args) throws IOException {
int s = 300;
BufferedImage image = new BufferedImage(s, s, BufferedImage.TYPE_INT_ARGB); //A!
Graphics2D g = image.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setPaint(Color.RED);
g.translate(s/2, s/2);
g.draw(createShape(s*4/10));
g.dispose();
ImageIO.write(image, "png", new File("temp.png"));
}
static Shape createShape(int r) {
GeneralPath path = new GeneralPath();
path.moveTo(0,-r);
lineTo(path, r, -3*Math.PI/10);
lineTo(path, r, 9*Math.PI/10);
lineTo(path, r, Math.PI/10);
lineTo(path, r, 13*Math.PI/10);
path.closePath();
path.append(new Ellipse2D.Float(-r, -r, 2*r, 2*r), false);
return path;
}
static void lineTo(GeneralPath path, float r, double angle) {
path.lineTo((float)(r*Math.cos(angle)), (float)(-r*Math.sin(angle)));
}
}
For more tips, see this thread:
http://forum.java.sun.com/thread.jspa?threadID=522483
#1; Fri, 13 Jul 2007 02:44:00 GMT

- Thank you so much, that was exactly what I needed.#2; Fri, 13 Jul 2007 02:44:00 GMT