Android obtains a snapshot of a photo.

Source: Internet
Author: User

When we are creating albums and uploading related applications, we need to take snapshots of images. At this time, we need to take snapshots of images.

Android has a BitmapFactory class to deal with such requirements.

The implementation steps are as follows:

1. parse the image file first (note that in order to save memory, set inJustDecodeBounds to true. In this way, only the size and size of the image are parsed)

BitmapFactory. Options BMP factoryoptions = new BitmapFactory. Options ();
BMP factoryoptions. inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory. decodeFile (imageFilePath, bmp factoryoptions );

2. Obtain the actual size of the image and calculate the ratio of the actual size to the size to be displayed.

Int heightRatio = (int) Math. ceil (BMP factoryoptions. outHeight/(float) DISPLAYHEIGHT );

Int widthRatio = (int) Math. ceil (BMP factoryoptions. outWidth/(float) DISPLAYWIDTH );

3. here is the key. To obtain the snapshot of this image, you need to set the inSampleSize attribute to the ratio calculated in the previous step. In this way, the image width and height are 1/ratio and the size is 1/ratio.

If (heightRatio> 1 & widthRatio> 1 ){
If (heightRatio> widthRatio ){
BMP factoryoptions. inSampleSize = heightRatio;
} Else {
BMP factoryoptions. inSampleSize = widthRatio;
}
}
4. Re-parse the image.

BMP factoryoptions. inJustDecodeBounds = false;
Bmp = BitmapFactory. decodeFile (imageFilePath, bmp factoryoptions );
5. In this way, a snapshot of the image is obtained.

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.