1 |
|
2 |
|
3 |
import java.awt.Color; |
4 |
import java.awt.Graphics2D; |
5 |
import java.awt.RenderingHints; |
6 |
import java.awt.image.BufferedImage; |
7 |
import java.io.IOException; |
8 |
|
9 |
import javax.imageio.ImageIO; |
10 |
import javax.servlet.ServletException; |
11 |
import javax.servlet.http.HttpServlet; |
12 |
import javax.servlet.http.HttpServletRequest; |
13 |
import javax.servlet.http.HttpServletResponse; |
14 |
|
15 |
|
16 |
|
17 |
// Image scaling :http://helpdesk.objects.com.au/java/how-do-i-scale-a-bufferedimage |
18 |
public class ImageServlet extends HttpServlet { |
19 |
private static final long serialVersionUID = 1L; |
20 |
|
21 |
|
22 |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
23 |
|
24 |
final int width = 400; |
25 |
final int height = 400; |
26 |
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); |
27 |
|
28 |
Graphics2D gfx = bufferedImage.createGraphics(); |
29 |
gfx.setColor( Color.white ); |
30 |
gfx.fillRect(0, 0, width, height); //Graphics2D has many various drawing methods |
31 |
gfx.setColor( Color.blue ); |
32 |
gfx.fillOval(10, 10, width-20, height-20); |
33 |
gfx.dispose(); //dispose when we are done with drawing |
34 |
|
35 |
|
36 |
//Downscale image to create a smoother looking one |
37 |
BufferedImage smallImage = new BufferedImage(width/2, height/2, BufferedImage.TYPE_INT_RGB); |
38 |
gfx = smallImage.createGraphics(); |
39 |
gfx.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); |
40 |
gfx.drawImage(bufferedImage, 0, 0, width/2, height/2, null); |
41 |
gfx.dispose(); |
42 |
|
43 |
|
44 |
|
45 |
response.setContentType("image/png"); |
46 |
ImageIO.write(smallImage, "png", response.getOutputStream() ); // use imageio.read to load a file to a bufferedimage |
47 |
|
48 |
} |
49 |
|
50 |
} |