Creating images with Java
In this paper we discuss and see how we can use Java to create, generate and manipulate simple images such as graphics and text. From this quick article, we have a good base to develop more sophisticated components for imaging.
Criandos images
Generally, the Swing components already have an image buffer, and only need to implement the paint () method. To create our images, we must also create a buffer for our image and then create an object of type java.awt.Graphics.
The class is a subclass of java.awt.image.BufferedImage java.awt.Image, which uses a memory block, and that’s where we create our image. In the constructor of the class will spend three parameters: width (image width), height (height image) and image type. Initially we will use the image type defined by BufferedImage.TYPE_INT_RGB, which allows transparent images. But this is beyond the scope of this article.
To create the chart that we use, we use the following code:
[Code] 1 int width = 200, height = 200;
2 BufferedImage buffer = new BufferedImage (width, height, BufferedImage.TYPE_INT_RGB);
3 buffer.createGraphics Graphics g = ()
How does that have an image buffer, which represents an image of 200 by 200 pixels in size. From there, we have a Graphics object that we use to draw the primitive desire.
The primitives are: points, lines, ovals (and circles), rectangles (and squares), among others.
Created the image, we will create a fund for her:
1 g.setColor (Color.White);
2 g.fillRect (0, 0, width, height);
With the method setColor () of the Graphics class, we set the color of the primitive that we draw. The fund is nothing more than a filled rectangle the size of the image itself, and for this we used the method fillRect (), I draw a Rectangle filled with the color reported in setColor (). Simple, no?
Now let’s draw a simple line in our image. Here’s the code:
1 g.setColor (Color.BLACK);
2 g.drawLine (0,0, width, height);
We define the new color that we use to design and send draw a line, the method drawLine (), stating the start and end points of the line.
Since we got here, let’s see some results to follow with the rest of the application, so that we may already have a visual idea of what we can do.
Let’s create a simple Swing application to display the image we created on the screen. Here is the code for the example:
01 import javax.swing .*;
02 import java.awt .*;
03 import java.awt.image .*;
04
(05 public class ExemploImagem
06 public static void main (String [] args) (
07 JFrame frm = new JFrame ("Test Image");
08 JPanel pan = new JPanel ();
09 JLabel lbl = new JLabel (criarImagem ());
10 pan.add (lbl);
11 frm.getContentPane (). Add (pan);
12 frm.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
13 frm.pack ();
14 frm.show ();
15 }
16
17 private static ImageIcon criarImagem () (
18 int width = 200, height = 200;
19 BufferedImage buffer = new BufferedImage (width, height, BufferedImage.TYPE_INT_RGB);
20 Graphics g = buffer.createGraphics ();
21 g.setColor (Color.White);
22 g.fillRect (0, 0, width, height);
23 g.setColor (Color.BLACK);
24 g.drawLine (0, 0, width, height);
25 return new ImageIcon (buffer);
26 }
27 }
In main () method we just Swing components to display the image, but watch out for the method criarImagem () which is what really interests us, because that’s where we are creating the image buffer and then return an object of type ImageIcon, which is the visual component of Swing which represents an image.
Running the application, we will see a window like this:

This first example, although simple and seemingly useless, it was important for us to start our experiment with the manipulation of images with Java.
Now, let us draw our example a little further, generating a pie chart. For this, we create a class, call PieChart, which will be a component that will create for us a pie chart from an array of value type int.
Here’s the implementation:
01 import javax.swing .*;
02 import java.awt .*;
03 import java.awt.image .*;
04
(05 public class PieChart
06
07 / / save the values to be displayed in the graph
08 private int [] values;
09 / / buffer stores the image drawn
10 private BufferedImage imageBuffer;
11 / / background color guard
12 private Color background;
13 / / store the image dimensions
14 private int width, height;
15 / / colors for the pieces of graph
16 private Color [] colors = (Color.BLUE, Color.GREEN, Color.RED,
17 Color.YELLOW, Color.ORANGE, Color.PINK,
18 Color.MAGENTA, Color.LIGHT_GRAY, Color.GRAY,
19th Color.BLACK);
20
21 /**
22 * Creates a class object that generates a pie chart.
23 * @ param values Array of integer values to be represented.
24 * @ param width Width of the image.
25 * @ param height Height of image.
26 * @ param background color, background image.
27 */
28 public PieChart (int [] values, int width, int height, Color background) (
29 if (values == null | | values.length <1 | |
30 width <0 | | height <0 | |
31 background == null) throw new IllegalArgumentException ();
32 this.value = values;
33 this.width = width;
34 this.height = height;
35 this.background = background;
36 CreateChart ();
37 }
38
39 /**
40 * Create the image internally.
41 */
42 private void CreateChart () (
43 imageBuffer = new BufferedImage (width, height, BufferedImage.TYPE_INT_RGB);
44 Graphics g = imageBuffer.createGraphics ();
45 g.setColor (background);
46 g.fillRect (0, 0, width, height);
47 int arc = 0;
48 int [] sizes = calculateAngles (values);
49 for (int i = 0, j = 0; i <sizes.length; i + +, j + +) (
50 if (j == 10) j = 0;
51st g.setColor (colors [j]);
52 g.fillArc (0, 0, width, height, arc, sizes [i]);
53 arc + = sizes [i];
54 }
55 }
56
57 /**
58 * Calculate the angles for each value reported.
59 * @ param value Value to have their angles calculated.
60 Array * @ return int with the angles for each value.
61 */
62 private int [] calculateAngles (int [] values) (
63 int [] angles = new int [values.length];
64 int total = 0;
65 / / calculate the sum total of the values
66 for (int i = 0; i <values.length; i + +) (
67 total + = values [i];
68 }
69 / / calculate the angles for each piece
70 for (int i = 0; i <values.length; + + i) (
71 angles [i] = (360 * values [i]) / total;
72 }
73 return angles;
74 }
75
76 /**
77 * Returns the image of the pie chart.
78 * @ return an object of type ImageIcon.
79 */
80 public ImageIcon getImageIcon () (
81 return new ImageIcon (imageBuffer);
82 }
83
84 /**
85 * Return the image buffer pie chart.
86 * @ return an object of type BufferedImage.
87 */
88 public BufferedImage getBufferedImage () (
89 imageBuffer return;
90 }
91 }
This class generates the image internally already in the constructor of the class. To get the image to be displayed, the method getImageIcon ().
To view the chart image generated, we can use the previous example and just change the line where the JLabel is created with the image, the following lines:
[Code] int a [] values = (20, 10, 60, 90, 180);
2 PieChart pie = new PieChart (values, 200, 200, Color.White);
3 JLabel lbl = new JLabel (pie.getImageIcon ()) [/ code]
See how simple it is? With a few lines of code, write a class that represents and draws a pie chart that is widely used in commercial applications.

This shows the power and ease of handling Java for this kind of application. The APIs provided by Sun are extremely powerful.
Sometimes we want not only to generate and display images, but can also save them to disk, and it will use the ImageIO class, package javax.imageio. This Java API allows to save images in JPEG and PNG. Unfortunately, for reasons of license, you can not save in GIF format. But there are third-party APIs to save the image in GIF format. The Google may give you a good help.
The procedure to write the disk image is simple, see:
ImageIO.write (pie.getBufferedImage (), “png”, new File (“img.png”));
The first parameter of the static method write () buffer is the image generated after the image type, which in this case is PNG and finally the File that represents where the file to be created.
Another option of the Write method () is informing an OutputStream instead of a File. With this, we can easily make a Java Servlet that generates an image. Example:
1 response.setContentType ("image / png");
2 response.getOutputStream OutputStream os = ();
3 ImageIO.write (buffer, "png", os);
4 os.close ();
In this case we change the content type to image / png, which is a PNG image. Then we spent the OutputStream response with the web client for the write () method, which writes the response image data generated and represented by buffer. Simple!
Sometimes we want to improve our image by adding a decorative text, and this is as simple as generating the image itself. We can even choose the font, the size and position of the text. Look at the example:
1 Font font = new Font ("Courier", Font.Bold, 30);
2 g.setColor (Color.BLUE);
3 g.setFont (font);
4 g.drawString ("Guj", 0.20);
The Font class, as the name suggests, is a font system. In its constructor, we reported the name of the source, its characteristics (for BOLD) and its size. Then just tell the chart text color, the font to be used to draw the text and sent to the method drawString (), String text informing the position (X, Y) in the image.

From then on you just use your imagination and develop their applications.