Use JSP to create reusable image backgrounds

Source: Internet
Author: User

There is a technology that can generate neat and fine-grained histograms in Java Server Pages (JSP), which can be used as a reusable background. To achieve reusability, you need to adjust the size of the image. You should also manage straight blocks to avoid them crossing the border of the graphic area. Then, you also need to encode the graphic data into a usable graphic format. We will use this Code This example describes the tips.
What do you need?

To start running the example given in this article, you need JDK 1.2 or a later version (http://java.sun.com ). You also need a web server that supports JSP. I tested this example on Tomcat.Com.sun.image.codec.jpegClass (released in Sun Java 2 SDK.

Reusable background

Since you want to have a reusable background, you should create a Java class to manage the layout, including the title area and external boundaries. For exampleFigureA.

Figure

As you can see, I have shadow on the title area and external boundaries. The title has a white border with a pixel width, and the graphic area has a thin black border. These boundaries increase the definition of shadows.

Boundaries are easy to generate. Using graphics2d objectFill ()Method to fill in a blue title rectangle, and then useDraw ()The method draws the boundary with its own colors.

The shadow effect is also very simple. First, useFill ()Method to draw a shadow. Then, draw the title at the offset of seven pixels. This offset produces a three-dimensional effect, so that the shadow effect is obtained.

For example

Suppose a company sells agricultural products. It needs a histogram to show sales. In practical applications, we need to obtain the data from a database or XML file, but for simplicity, we assume that the sales data is saved in the following two Arrays:
String datanames [] = {"apple", "orange", "Peach", "Lemon", "grapefruit "};
Int datavalues [] = {11, 62, 33,102, 50 };

The first array stores various agricultural products sold by the company. The second array corresponds to the sales of each agricultural product.

Prepare the Histogram

The histogram will be displayed and saved in JPEG format, so we need to set the mime correctly, that is, the content type. The browser uses the MIME type to determine how to respond. The following code sets the MIME type:
Response. setcontenttype ("image/JPEG ");

Next, we need an object that represents the image. Java 2D API supportBufferedimageClass, which provides a method to store and manage pixel data in the memory. We want the image to be colored, so we useType_int_rgbGraph type.WidthAndHeightThe two integer data are used to specify the width and height of the image in pixels:
Bufferedimage Bi = new bufferedimage (width, height, bufferedimage. type_int_rgb );

Now we have a bufferedimage object. We can callCreategraphics ()Method To SetGraphics2dContent:
Graphics2d bicontext = Bi. creategraphics ();

Width, height, and maximum value

CreateProgramYou need to set according to the importance of the image and the overall layout of the page.WidthParameters. The Graphic Element automatically adjusts its size based on the change in the image width.

The width and boundary area of the title, and the longest straight square of the image need to be determined accordingWidthParameters are calculated. This aims to ensure that all graphic elements do not exceed the width of the image and cross the right border of the image.

The number of data entries to be displayed determines the numberHeightParameters. If a new element is addedDatavalues []AndDatanames []Array, then the Image Height should increase accordingly to adapt to the size of the area to be displayed.

MaximumThis parameter is used for the longest straight square. Then, the width of other direct squares is relativeMaximumCalculation:
Int barwidth = (innerwidth * currentvalue)/maximum;

The aboveAlgorithmUsedMaximumAnd graphicalInnerwidth(Graphic area) these two values make sure that the straight square will followWidthAuto scaling when the value changes.

Display graphic background

To display the image, we need to create a background image and add the image data. First, createGraphbgObject and call itsDraw ()Method:
Graphbg GR = new graphbg ();
Gr. Draw (bicontext, width, height, "farm produce", "overall average:" + average );

Draw ()Parameters of the method include the image content,Bicontext, WidthAndHeight,GraphbgClass to determine the width and height of the title and graphic area. Finally, computingAverageAdd the data value to the text displayed in the title.

Create cube

The vertical coordinate (Y axis) of each straight square is calculated according to the following formula:Y_pos = I * displayheight + headeroffset. WhereDisplayheightEqual to the text height on the straight square plus the height of the straight square,HeaderoffsetVertical distance from the top of the image, including the title area and the height of the shadow.

I used the technology that previously created the title boundary to create these straight blocks and their boundary. I subtract a pixel from the width and height of the straight boundary so that each straight boundary looks like a red boundary, and draw the inner boundary on the white background to make the subtraction effect easy.

Encoding

We have already created this image in the memory. Now we encode it and display it to the user. We cannot use the default JSP output stream to process JPEG, so we need to useResponse. getoutputstream ()Obtain the stream from the response object. We can use the output stream to createJpegimageencoderObject and call itsEncode (), PassBufferedimageObject:
Required imageencoder encoder = required codec. createjpegencoder (output );
Encoder. encode (BI );

The generated image is relatively small and takes up only 13.7 KB of capacity.FigureBThe final results are given:

Figure B

Either way,Index. jspThe output is a JPEG image. You can save the image to your desktop or press the printscreen key to capture the image. If you want to display multiple images on the same page or introduce the images into other content, you can useIMGMark (<IMG src = "index. jsp">), And then place the graph as needed, such as using a table.

Perhaps one of the oldest Internet technologies used to dynamically generate images can achieveOthersTask. Imagine you need to record the number of visitors (similar to the number of ad clicks) in this figure, then you needIndex. jspTo implement tasks such as click count, database, or file access. You can process these tasks in the background without switching to users using the buffer page.

Conclusion

In this article, we have tested a histogram that produces a neat and comfortable appearance. We cleverly handled the changes in the image size and encoded the image into JPEG format, and discussed how to modify the HTML code to place the final image on different pages.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.