Create images in Java applications

Source: Internet
Author: User

Synthesize Images

You do not have to read all the images from the file-you can create your own images. To create your own Image, the most flexible method is to use a BufferedImage object, which is a subclass of the Image class and stores the Image data in an accessible buffer. It also supports various methods for storing pixel data: using or without alpha channels, different color models, and various precision of color components. The ColorModel class provides a flexible way to define various color models and use them with BufferedImage objects. To understand the basic knowledge of color models, we will only use one default color model, the color component consists of an RGB value and a buffer type (storing an 8-bit RGB color value plus an alpha channel. This buffer type is specified by the constant TYPE_INT_ARGB in the BufferedImage class, which means that each pixel uses an int value. The value of each pixel is stored in 8 bytes as an alpha component plus an RGB color component. We can create a BufferedImage object of this type with the given width and height. The Code statement is as follows:

Int width = 200;
Int height = 300;
BufferedImage image = new BufferedImage (width,
Height, BufferedImage. TYPE_INT_ARGB );

This Code creates a BufferedImage object that represents an image of 200 pixels in width and 300 pixels in height. To apply this image, we need to have a graphical context, and the createGraphics () method of the BufferedImage object returns a Graphics2D object related to the image:

Int width = 200;
Graphics2D g2D = image. createGraphics ();

Operations on g2D objects modify the pixels of the BufferedImage object image. With this object, you are now fully capable of applying the BufferedImage object. You can draw shapes, images, GeneralPath objects, or anything else, and set alpha composite objects for the graphic context. You also have all the affinsic deformation capabilities provided by Graphics2D objects.

To obtain a single pixel from a BufferedImage object, you can call its getRGB () method and provide the x and y coordinates of the pixel as the int type parameter. This pixel is returned in the int type in the TYPE_INT_ARGB format. It consists of four 8-bit values (representing the alpha value and the RGB color component) and a 32-bit character. GetRGB () also has an overloaded version, which returns a pixel array from some image data. You can also set a single pixel by calling the setRGB () method. The first two parameters are the coordinates of the pixel, and the third parameter is the value to be set. The type is int. This method also has a version that can set the value of the pixel array.

Now we have completed pixel operations. Next we will create an applet that will make the BufferedImage object animated on the Wrox logo background. Our example also demonstrates how to make the image local transparent. The basic content of the applet is as follows:

Import java. awt .*;
Import java. awt. image .*;
Import java. awt. geom .*;
Import javax. swing .*;

Public class ImageDrawDemo extends JApplet
{
// The init () method to initialize everything...
// The start () method to start the animation...
// The stop () method to stop the animation...
// The ImagePanel class defining the panel displaying the animation...
// Data members for the applet...
}

  Create an image

A child image is a small image that can be drawn in a static image to create an animation. To create an animation effect, you only need to draw a child image at different positions and directions over time. Of course, the deformation of the coordinate system can simplify a lot. Games often use sub-graphics-since you only need to draw sub-graphics on a static background, you can greatly reduce the time spent by the animation processor. Our interest in using BufferedImage objects means that we will no longer focus on the best technology to reduce processor time, but focus on understanding how to create and use images within a program.

Our BufferedImage object looks like the image in 1:

Figure 1. BufferedImage subgraph

This image is a square with spriteSize as the side length. The dimension values of other parts of the image are related to the edge length. In fact, there are only two geometric entities, one line and one circle, all of which are repeated at different positions and directions. If we create a Line2D. the Double object represents a line and creates an Ellipse2D object. the Double object represents the circle, so we can draw the entire image by moving the user coordinate system and drawing one or other objects of the two objects.

If it is based on the real object-oriented method, a class should be defined to represent a sub-graph, which may be a subclass of BufferedImage, but since we are exploring the techniques to use BufferedImage objects, therefore, using a createSprite () method to draw subgraphs on the BufferedImage object is more suitable for our purposes. Because this method is only a member of our applet Class, we will add data members for the applet to store any required data. You can insert the data member we use into the applet Class, as shown below:

Double totalAngle; // Current angular position of sprite
Double spriteAngle; // Rotation angle of sprite about its center
ImagePanel imagePanel; // Panel to display animation

BufferedImage sprite; // Stores reference to the sprite
Int spriteSize = 100; // Diameter of the sprite
Ellipse2D. Double circle; // A circle-part of the sprite
Line2D. Double line; // A line-part of the sprite

// Colors used in sprite
Color [] colors = {Color. red, Color. yellow, Color. green, Color. blue,
Color. cyan, Color. pink, Color. magenta, Color. orange };

Java. util. Timer timer; // Timer for the animation
Long interval = 50; // Time interval msec between repaints

The general purpose of these Members can be clearly seen from the comments. Next, let's take a look at how code is used during development.

The first thing to do with the createSprite () method is to create the BufferedImage object sprite, And then we need a Graphics2D object for painting on the sprite image. The following code completes these operations:

BufferedImage createSprite (int spriteSize)
{
// Create image with RGB and alpha channel
BufferedImage sprite = new BufferedImage (spriteSize, spriteSize,
BufferedImage. TYPE_INT_ARGB );

Graphics2D g2D = sprite. createGraphics (); // Context for buffered image
// Plus the rest of the method...
}

The width and height of a sprite object are spriteSize, and the image type is TYPE_INT_ARGB. That is to say, the alpha value and color component of each pixel are stored in a separate int value, the color is stored in 8-bit red, green, and blue components. This means that our sprite image will occupy 40,000 bytes, which is only a small part of the memory occupied by browsing a Web page. This does not affect the download time of the web page, because when executing the applet, this part of memory is allocated on the local machine. In addition to the HTML file content of the webpage, the download time also depends on the size of the. class file of the applet and the image or other files downloaded during its execution.

    Create a transparent background

In sprite images, the alpha channel is important because we want the background to be completely transparent. In the painting process, only the sprite object itself should be visible, rather than the entire 100x100 rectangular image. We can easily achieve this goal by first making the entire sprite image area transparent (that is, the alpha value is 0.0f) and then drawing the image we want to draw on it, make it opaque (the alpha value is 1.0f ). The following code makes the entire image transparent:

// Clear image with transparent alpha by drawing a rectangle
G2D. setComposite (AlphaComposite. getInstance (AlphaComposite. CLEAR, 0.0f ));
Rectangle2D. Double rect = new Rectangle2D. Double (0, spriteSize, spriteSize );
G2D. fill (rect );

First, we use the AlphaComposite object to set the alpha merging value according to the CLEAR rule, set the color component to zero, and set the alpha value to 0.0f to make it transparent. Then we fill in a rectangle that overwrites the entire image area. We do not need to set the color value, because according to the CLEAR rule, the foreground and background color of each pixel are both zero, so neither of them is involved in pixel generation. But we still need to fill the rectangle, because this will determine the pixels of the image to be operated.

Here, we can learn a little about how to control the image quality.

  Color fine-tuning

For many aspects of the coloring operation, there is a problem of selecting between quality and speed. Coloring is like most things-quality is costly, and the cost here is the processing time. All coloring operations have default settings. One of the options is available. The default settings are platform-specific. However, you can choose one by calling the setRenderingHint () method of the Graphics2D object used for coloring. Although there are only some minor adjustments, these minor adjustments will not take effect if your computer does not support the coloring operation options that match your specified minor adjustments.

By adding the following call to the createSprite () method, we can ensure the best effect possible by our alpha synthesis operation.

BufferedImage createSprite (int spriteSize)
{
// Create image with RGB and alpha channel
BufferedImage sprite = new BufferedImage (spriteSize, spriteSize, BufferedImage. TYPE_INT_ARGB );

Graphics2D g2D = sprite. createGraphics (); // Context for buffered image

// Set best alpha interpolation quality
G2D. setRenderingHint (RenderingHints. KEY_ALPHA_INTERPOLATION,
RenderingHints. VALUE_ALPHA_INTERPOLATION_QUALITY );

// Clear image with transparent alpha by drawing a rectangle
G2D. setComposite (AlphaComposite. getInstance (AlphaComposite. CLEAR, 0.0f ));
Rectangle2D. Double rect = new Rectangle2D. Double (0, spriteSize, spriteSize );
G2D. fill (rect );

// Plus the rest of the method...
}

The RenderingHints class defines a variety of coloring fine-tuning that are stored in the Graphics2D object of a ing set. The parameter of the setRenderingHint () method is a key and the corresponding key value. In our code, the first parameter represents the key for fine-tuning alpha synthesis, and the second parameter represents the fine-tuning value. Other possible values of this fine-tuning include VALUE_ALPHA_INTERPOLATION_DEFAULT, which indicates the platform default value and VALUE_ALPHA_INTERPOLATION_SPEED, which indicates the pursuit of speed rather than quality.

You can also fine-tune the following keys:

Key description
KEY_ANTIALIASING determines whether to use anti-aliasing. When colored lines with Skewed angles, a set of tiered pixel lines are usually arranged to make the line look uneven. This line is often called a jagged image. Anti-aliasing is a technology that sets the pixel brightness of a line with a tilt angle to make the line look smoother. Therefore, this fine-tuning is used to determine whether it takes time to reduce the amount of time on the jagged image when the colored line has a skewed angle. Possible values include VALUE_ANTIALIAS_ON, _ OFF, And _ DEFAULT.
KEY_COLOR_RENDERING controls the color coloring method. Possible values include VALUE_COLOR_RENDER_SPEED, _ QUALITY or _ DEFAULT.
KEY_DITHERING controls how to handle jitter. Jitter is the process of synthesizing a larger range of colors with a limited set of colors by coloring adjacent pixels to produce new color illusion that is not in this set of colors. Possible values include VALUE_DITHER_ENABLE, _ DISABLE, and _ DEFAULT.
KEY_FRACTIONALMETRICS text quality. Possible values include VALUE_FRACTIONALMETRICS_ON, _ OFF, And _ DEFAULT.
KEY_INTERPOLATION determines how to perform interpolation.

When deformation is performed on a source image, the transformed pixels rarely match the target pixel location. In this case, the color value of each transformed pixel must be determined by the surrounding pixel.

Interpolation is to implement the above process. There are many available technologies. Possible value, which ranges from the most to the least by processing time, is VALUE_INTERPOLATION_BICUBIC, _ BILINEAR or _ NEAREST_NEIGHBOR.

KEY_RENDERING identifies the coloring technology and balances the speed and quality. Possible values include VALUE_RENDERING_SPEED, _ QUALITY, and _ DEFAULT.

KEY_TEXT_ANTIALIASING determines whether the anti-aliasing feature is used for text coloring. Possible values include VALUE_TEXT_ANTIALIASING_ON, _ OFF, And _ DEFAULT.

We are far away. Let's go back to drawing sprite ......

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.