Get the App
SLTechnology News&Howtos  ›  Development  › 

How to generate pictures dynamically with Servlets

Shulou Source: shulou.com Published: 2022-06-02 13:32:08 09月23日 Update

This article introduces how to use Servlets to dynamically generate pictures, the content is very detailed, interested friends can use for reference, I hope it can be helpful to you.

Image I Dot O package and its requirements for JDK

If your servlet wants to generate an image dynamically, you first need image I servlet O, specifically, you need to generate an image in response to a HTTP request. The core Java API does not directly provide the ability to maintain any images. However, you can use Sun's Java 1.1 class library to do image I Dot O. And the 1.2 version of Sun's image IMaple O provides packets to encode and decode JPEG images. Because this code is not part of the core API in the com.sun package, nor is it a standard extension package, it affects the portability of the code.

It will be much easier to use jdk 1.2 than jdk 1.1. This paper introduces the implementation method under jdk 1.2. The example has three steps: create, draw, and save. In this example, only show how to draw an ellipse, of course, you can modify it according to your needs. The example uses the com.sun.image.codec.jpeg package to generate the JPEG file. If you want to generate GIF files, you can use a third-party package, such as Acme Labs's GIF Encoder.

1. Create a BufferedImage object with the appropriate size:

BufferedImage

Image = new BufferedImage (width, height, BufferedImage.TYPE_INT_RGB)

two。 Draw the image you want on the image object. Suppose you want a white background, you need to draw a rectangle filled with white. Otherwise, the background will be black by default:

Graphics g = image.getGraphics ()

G.setColor (Color.white)

G.fillRect (0pen 0, width, height)

G.setColor (Color.red)

G.drawOval (0,0, width, height)

3. Use the com.sun.image.codec.jpeg package to output BufferedImage:

Response.setContentType ("image/jpeg")

ServletOutputStream out = response.getOutputStream ();

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder (out)

Encoder.encode (image)

Out.close (); [@ more@]

On how to use Servlets to dynamically generate pictures to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Tags: Generate image dynamic picture code content object file more core white background help good appropriate three examples interest function boy Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple vpn Huawei MariaDB Microsoft