Android bitmap class-implements image segmentation, scaling, and Rotation

Source: Internet
Author: User

Bitmap is one of the most important types of Image Processing in the Android system. It can be used to obtain image file information, perform image cutting, rotation, scaling, and other operations, and save image files in a specified format. This article focuses on how to use bitmap to implement these functions from the application perspective.
 
I. Generation of Bitmap
 
1.1 bitmapfactory decode bitmap

 
Bitmap is implemented in the Android. graphics package. However, bitmap constructor is private and cannot be instantiated outside. It can only be instantiated through JNI. This must be because a helper class provides an interface for creating bitmap, and the implementation of this class instantiates bitmap through the JNI interface. This class is bitmapfactory.

 

Figure 1: Main bitmapfactory methods and options

Bitmapfactory can be used to calculate bitmap from a specified file, decodefile (), or decoderesource () in image resources.

1.2 decode options

You can specify a bitmapfacotry. options when using decodefile ()/decoderesource.

You can specify the decode option by using the following attributes of options:

  • Inpreferredconfig specifies the encoding used in the phone when the decode is in the memory. The optional value is defined in bitmap. config. The default value is argb_8888.
  • If the value of injustdecodebounds is set to true, the image data is not completely decoded, that is, the return value of decodexyz () is null, but the outabc of options solves the basic information of the image.
  • Insamplesize specifies the decode scaling ratio.

Using these options values, you can efficiently get a thumbnail.

 

Figure 2: bitmapfactory. decodefile ()

Set injustdecodebounds = true first, and call decodefile () to obtain the basic information of the image [step #2 ~ 4];

Use the image width (or height, or comprehensive) and target width to obtain the insamplesize value, set injustdecodebounds to false, and call decodefile () to obtain the complete image data [step #5 ~ 8].

First, get the proportion and then read the data. If you want to read a scaled-down graph, it will significantly save content resources. Sometimes a large number of thumbnails are read, which is more obvious.

 

Ii. Using bitmap and matrix for Image Transformation

Bitmap can be combined with matrix to achieve image cutting, rotation, scaling, and other operations.

 

Figure 3: bitmap Method

Use the source bitmap to generate a new bitmap through transformation:

public static Bitmap createBitmap(Bitmap source, int x, int y, intwidth, int height,             Matrix m, boolean filter)  public static Bitmap createBitmap(Bitmap source, int x, int y, intwidth, int height) public static Bitmap createScaledBitmap(Bitmap src, int dstWidth,              int dstHeight,boolean filter)  

The first method is the final implementation, and the last two are only the encapsulation of the first method.

The second method can be used to dig out a part from the specified area (X, Y, width, height) in the source bitmap to achieve cutting. The third method can scale the source bitmap to the bitmap of dstwidth x dstheight.

Set the rotate (via setrotate () or scale (via setscale () of matrix to pass in the first method to achieve rotation or scaling.

 

Figure 4: bitmap Rotation

3. Save image files

The data in the bitmap after image transformation can be saved to the image compression file (JPG/PNG ).

Figure 5: Save bitmap data to a file

During this operation, bitmap. the format parameter of the compress () method can be set to JPEG or PNG. The quality parameter can be set to compression quality. fout is the output stream, where fileoutputstream is a subclass of outputstream.

To sum up, this article introduces how to use Bitmap-using bitmap to read and write image files, and using bitmap to achieve image cutting, rotation, scaling, and transformation.

When developing image browsers and other software, it is often necessary to display the thumbnail of an image. In general, we need to take a thumbnail of the image according to a fixed size, generally, the thumbnails are obtained using the decodefile method of bitmapfactory, and then transmitted to bitmapfactory. the option type parameter is used to retrieve the thumbnail. In option, the attribute value insamplesize indicates that the thumbnail size is one of the fraction of the original image size, that is, if the value is 2, the width and height of the thumbnail are 1/2 of the original image, and the image size is 1/4 of the original size.

However, it is more difficult to obtain a fixed-size thumbnail. For example, we want to make the height of the thumbnail of an image of different sizes PX, and ensure that the image is not distorted, what should we do? We can't always load the original image into the memory for scaling. You must know that in mobile development, memory is very valuable, and a K image, after loading the occupied memory, what is the limit of 100 kb?

After research, we found that there is an injustdecodebounds attribute in options. After a research, we finally understood what it meant. This is what E in the SDK said.

If set to true, the decoder will return NULL (no bitmap), but the out... fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.

This means that if this value is set to true, the actual bitmap will not be returned and the memory space will not be allocated to it, but only some decoded boundary information, that is, the image size information, will be included, then the corresponding method will come out. By setting injustdecodebounds to true, get outheight (original image height) and outwidth (original image width), and then calculate an insamplesize (zoom value ), then you can take the image. Note that the insamplesize may be smaller than 0 and must be determined.

The Code is as follows:

Framelayout Fr = (framelayout) findviewbyid (R. id. framelayout01); bitmapfactory. options = new bitmapfactory. options (); options. injustdecodebounds = true; // obtain the width and height of the image. Bitmap = bitmapfactory. decodefile ("/sdcard/test.jpg", options); // at this time, the returned BM is null options. injustdecodebounds = false; // calculate the zoom ratio of int be = (INT) (options. outheight/(float) 200); If (be <= 0) be = 1; options. insamplesize = be; // re-read the image. Note that options should be added this time. set injustdecodebounds to false. Bitmap = bitmapfactory. decodefile ("/sdcard/test.jpg", options); int W = bitmap. getwidth (); int H = bitmap. getheight (); system. out. println (W + "" + H); imageview IV = new imageview (this); IV. setimagebitmap (Bitmap );

In this way, we can read large images without memory overflow. If you want to save the compressed image on the sdcard, It's easy:

File file=new File("/sdcard/feng.png");try {   FileOutputStream out=new FileOutputStream(file);   if(bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)){      out.flush();      out.close();   }} catch (FileNotFoundException e) {    // TODO Auto-generated catch block    e.printStackTrace();} catch (IOException e) {    // TODO Auto-generated catch block    e.printStackTrace();}

OK, so that the image is saved in the/sdcard/feng.png file.

4. Use thumbnailutils to generate thumbnails of images or videos (new features introduced by android2.2)

The thumbnailutils tool class is used to implement thumbnails. This tool class is powerful and easy to use. It provides a constant and three methods. Using these constants and methods, you can easily and quickly implement the thumbnails of images and videos. The three methods are as follows:

Bitmap createvideothumbnail (string filepath, int kind) // you can see from the method name that this method is used to generate a video thumbnail. // Parameter: // filepath: video file path // kind: file type, which can be mini_kind or micro_kindbitmap extractthumbnail (bitmap source, int width, int height, int options) // This method is used to generate a thumbnail of a specified size. // Parameter: // Source: Source bitmap object to be thumbnail created // width: width of the generated target // Height: height of the generated target // options: the bitmap extractthumbnail (bitmap source, int width, int height) option provided during thumbnail extraction // This method is used to generate a thumbnail of a specified size. // Parameter: // Source: Source bitmap object to be thumbnail created // width: width of the generated target // Height: height of the generated target

 

Refer:

Http://www.cnblogs.com/Soprano/articles/2577152.html

Http://w1985chun.iteye.com/blog/1161950

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.