- Generating Images in Java Servlets
- Like this article? We recommend
- Like this article? We recommend
- Like this article? We recommend
- Sending Image Files from Servlets
- # Creating Images Programmatically
- # Creating a simple image programmatically and displaying it
- # Save an Image to disk
- # Setting individual pixel’s color in BufferedImage
- # Specifying image rendering quality
- # Creating an image with BufferedImage class
- # Editing and re-using image with BufferedImage
- # How to scale a BufferedImage
- # Remarks
- How to create a random pixel image in Java
- Prerequisite
- Color image to random pixel image
- Import the required classes
- Create the class
- Create BufferedImage
- Random pixel image code
- Generate random pixel
- Set new pixel value
- Write image
- Final code
Generating Images in Java Servlets
Servlets are Java programs that run on a Web server. These Java servlets can be used to generate dynamic Web pages. What’s more, the pages are not limited to text and thus can be images. Y. Daniel Liang demonstrates here how to generate images in Java servlets.
This article is derived from the book Rapid Java Application Development Using JBuilder 4/5/6 (Prentice Hall PTR, 2001), by Y. Daniel Liang.
Like this article? We recommend
Like this article? We recommend
Like this article? We recommend
Servlets are Java programs that run on a Web server. Java servlets can be used to generate dynamic Web pages. The pages are not limited to text, and they can be images. This article demonstrates generating images in Java serlvets.
Sending Image Files from Servlets
To send contents as images, the content type must be set to image/gif, image/jpg, or image/png. For example, to send GIF images, you need to set the content type as follows:
response.setContentType("image/gif");
Here, response is an instance of HttpServletResponse. Because images are binary data, you have to use a binary output stream:
OutputStream out = response.getOutputStream();
You can then create an instance of the Image class filled with content. Before the image is sent to a browser, it must be encoded into a format acceptable to the browser. Image encoders are not part of Java API, but several free encoders are available. One of them is the GifEncoder class from Acme.
Use the following statement to encode and send the image to the browser:
new GifEncoder(image, out, true).encode();
Here is an example of a servlet that dynamically generates the flag of a country, as shown in Figure 1.
package servletdemo; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.awt.Image; import javax.swing.ImageIcon; import Acme.JPM.Encoders.GifEncoder; public class ImageContent extends HttpServlet < /** Process the HTTP Get request */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < response.setContentType("image/gif"); OutputStream out = response.getOutputStream(); // Obtain an image icon ImageIcon imageIcon = new ImageIcon("c:\\radjb\\image\\" + request.getParameter("country") + ".gif"); // Obtain image from image icon Image image = imageIcon.getImage(); // Get the image // Encode the image and send to the output stream new GifEncoder(image, out, true).encode(); out.close(); // Close stream >>
Figure 1 The servlet returns an image of the country flag.
# Creating Images Programmatically
# Creating a simple image programmatically and displaying it
class ImageCreationExample static Image createSampleImage() // instantiate a new BufferedImage (subclass of Image) instance BufferedImage img = new BufferedImage(640, 480, BufferedImage.TYPE_INT_ARGB); //draw something on the image paintOnImage(img); return img; > static void paintOnImage(BufferedImage img) // get a drawable Graphics2D (subclass of Graphics) object Graphics2D g2d = (Graphics2D) img.getGraphics(); // some sample drawing g2d.setColor(Color.BLACK); g2d.fillRect(0, 0, 640, 480); g2d.setColor(Color.WHITE); g2d.drawLine(0, 0, 640, 480); g2d.drawLine(0, 480, 640, 0); g2d.setColor(Color.YELLOW); g2d.drawOval(200, 100, 240, 280); g2d.setColor(Color.RED); g2d.drawRect(150, 70, 340, 340); // drawing on images can be very memory-consuming // so it's better to free resources early // it's not necessary, though g2d.dispose(); > public static void main(String[] args) JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Image img = createSampleImage(); ImageIcon icon = new ImageIcon(img); frame.add(new JLabel(icon)); frame.pack(); frame.setVisible(true); > >
# Save an Image to disk
public static void saveImage(String destination) throws IOException // method implemented in "Creating a simple image Programmatically and displaying it" example BufferedImage img = createSampleImage(); // ImageIO provides several write methods with different outputs ImageIO.write(img, "png", new File(destination)); >
# Setting individual pixel’s color in BufferedImage
BufferedImage image = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB); //you don't have to use the Graphics object, you can read and set pixel color individually for (int i = 0; i 256; i++) for (int j = 0; j 256; j++) int alpha = 255; //don't forget this, or use BufferedImage.TYPE_INT_RGB instead int red = i; //or any formula you like int green = j; //or any formula you like int blue = 50; //or any formula you like int color = (alpha <24) | (red <16) | (green <8) | blue; image.setRGB(i, j, color); > > ImageIO.write(image, "png", new File("computed.png"));
# Specifying image rendering quality
static void setupQualityHigh(Graphics2D g2d) g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // many other RenderingHints KEY/VALUE pairs to specify > static void setupQualityLow(Graphics2D g2d) g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); >
A comparison of QUALITY and SPEED rendering of the sample image:
# Creating an image with BufferedImage class
int width = 256; //in pixels int height = 256; //in pixels BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); //BufferedImage.TYPE_4BYTE_ABGR - store RGB color and visibility (alpha), see javadoc for more info Graphics g = image.createGraphics(); //draw whatever you like, like you would in a drawComponent(Graphics g) method in an UI application g.setColor(Color.RED); g.fillRect(20, 30, 50, 50); g.setColor(Color.BLUE); g.drawOval(120, 120, 80, 40); g.dispose(); //dispose graphics objects when they are no longer needed //now image has programmatically generated content, you can use it in graphics.drawImage() to draw it somewhere else //or just simply save it to a file ImageIO.write(image, "png", new File("myimage.png"));
# Editing and re-using image with BufferedImage
BufferedImage cat = ImageIO.read(new File("cat.jpg")); //read existing file //modify it Graphics g = cat.createGraphics(); g.setColor(Color.RED); g.drawString("Cat", 10, 10); g.dispose(); //now create a new image BufferedImage cats = new BufferedImage(256, 256, BufferedImage.TYPE_4BYTE_ABGR); //and draw the old one on it, 16 times g = cats.createGraphics(); for (int i = 0; i 4; i++) for (int j = 0; j 4; j++) g.drawImage(cat, i * 64, j * 64, null); > > g.setColor(Color.BLUE); g.drawRect(0, 0, 255, 255); //add some nice border g.dispose(); //and done ImageIO.write(cats, "png", new File("cats.png"));
# How to scale a BufferedImage
/** * Resizes an image using a Graphics2D object backed by a BufferedImage. * @param srcImg - source image to scale * @param w - desired width * @param h - desired height * @return - the new resized image */ private BufferedImage getScaledImage(Image srcImg, int w, int h) < //Create a new image with good size that contains or might contain arbitrary alpha values between and including 0.0 and 1.0. BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TRANSLUCENT); //Create a device-independant object to draw the resized image Graphics2D g2 = resizedImg.createGraphics(); //This could be changed, Cf. http://stackoverflow.com/documentation/java/5482/creating-images-programmatically/19498/specifying-image-rendering-quality g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); //Finally draw the source image in the Graphics2D with the desired size. g2.drawImage(srcImg, 0, 0, w, h, null); //Disposes of this graphics context and releases any system resources that it is using g2.dispose(); //Return the image used to create the Graphics2D return resizedImg; >
# Remarks
(opens new window) may significantly improve the speed of drawing operations, but also has its drawbacks: its contents may be lost at any moment and they may have to be redrawn from scratch.
How to create a random pixel image in Java
In this project we will learn to create a random pixel image using Java programming language.
Prerequisite
It is assumed that you have completed the projects titled How to read and write image file in Java and How to get and set pixel value in Java before starting this project.
Color image to random pixel image
Creating a random image is based on random numbers. We have to perform the 3 steps to get the random pixel image.
- Set the dimension of the image.
For this project we will take Width = 640 and Height = 320
Import the required classes
Create a new file and save it by the name RandomImage.java. Open the file and import the following:
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
Create the class
Next we will create the class by the name RandomImage and inside the class we will have the main() method. For this we will write:
public class RandomImage
public static void main(String args[])throws IOException
// some code goes here.
>//main() ends here
>//class ends here
Create BufferedImage
To create a random image we first have to create a BufferedImage object img and set its dimensions to 640x320. And we will create a File object f and set it to null. So, we will write the following code:
//image dimension
int width = 640;
int height = 320;
//create buffered image object img
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
//file object
File f = null;
Random pixel image code
We know that an image is made up of pixels which we can represent in 2D co-ordinate. So, we will create two variables x and y and use two for loops to traverse each pixels.
for(int y = 0; y < height; y++)
for(int x = 0; x < width; x++)
// some code goes here.
>
>
Generate random pixel
In Java, to generate a random number we will use the random() method of the Math class. This generates a value greater than or equal to 0 and less less than 1. That is, we will get values like, 0.0 or 0.1 or 0.99999 etc. But we will never get 1.
We know that Alpha, Red, Green and Blue can take any integer value from 0 to 255. So, to get a value in the range 0 to 255 we will first multiply the random number with 256 and then convert the result to integer.
So, to get the random number we will write, Math.random()*256 which will give us a value greater than or equal to 0 and less than 256. Something like 0 or 123.45 or 255.999999. It will never give us 256.
Now to get the integer value we will type cast the floating value to int data type. For this we will write:
So, in order to generate random Alpha, Red, Green and Blue value we will write:
int a = (int)(Math.random()*256); //alpha
int r = (int)(Math.random()*256); //red
int g = (int)(Math.random()*256); //green
int b = (int)(Math.random()*256); //blue
Set new pixel value
Now, we will set the new pixel value. For this we will write:
Write image
After the for loop ends we will write the image file. For this we will write the following code:
try
f = new File("D:\\Image\\Output.jpg");
ImageIO.write(img, "png", f);
>catch(IOException e)
System.out.println(e);
>
Final code
/**
* File: RandomImage.java
*
* Description:
* Create a random color image.
*
* @author Yusuf Shakeel
* Date: 01-04-2014 tue
*/
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class RandomImage
public static void main(String args[])throws IOException
//image dimension
int width = 640;
int height = 320;
//create buffered image object img
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
//file object
File f = null;
//create random image pixel by pixel
for(int y = 0; y < height; y++)
for(int x = 0; x < width; x++)
int a = (int)(Math.random()*256); //alpha
int r = (int)(Math.random()*256); //red
int g = (int)(Math.random()*256); //green
int b = (int)(Math.random()*256); //blue
int p = (a<<24) | (r<<16) | (g<<8) | b; //pixel
img.setRGB(x, y, p);
>
>
//write image
try
f = new File("D:\\Image\\Output.png");
ImageIO.write(img, "png", f);
>catch(IOException e)
System.out.println("Error: " + e);
>
>//main() ends here
>//class ends here