[Android] The Image taking, screenshot taking, saving, and display in the ImageView Control

Source: Internet
Author: User
Tags dcim folder

[Android] takes a photo, saves it, and displays it in the ImageView control.

Recently, I am working on Android projects, some of which involve image processing content. the following describes how to call the Camera application to take a photo and save it in the ImageView control.
PS: The author purchased the first line of Android code: Guo Lin, which was completed with reference to the content. (The layout and Application in the previous section are recommended ). there are a lot of such materials on the Internet. The author only shares some content with beginners online at the same time, hoping to help you.
First, set activity_main.xml to the LinearLayout layout and android: orientation =Vertical

 

   
  

ThenMainActivity. java FileIn the public class MainActivity extends Activity to modify the source code. add custom variables:

 

// Custom variable public static final int TAKE_PHOTO = 1; public static final int CROP_PHOTO = 2; private Button takePhotoBn; private ImageView showImage; private Uri imageUri; // image path private String filename; // image name
Add a function to enable the click photo function:

 

@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); takePhotoBn = (Button) findViewById (R. id. button1); showImage = (ImageView) findViewById (R. id. imageView1); // click the Photo Button to take a Photo of takePhotoBn. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// image name time name: SimpleDateFormat format = new SimpleDateFormat (yyyyMMddHHmmss); Date date = new Date (System. currentTimeMillis (); filename = format. format (date); // create a File object to store the root directory of the SD card of the image to be taken. // File outputImage = new File(Environment.getExternalStorageDirectory(),test.jpg); // store it to the DCIM folder File path = environ. getExternalStoragePublicDirectory (Environment. DIRECTORY_DCIM); File outputImage = new file(path,filename=.jpg); try {if (outputImage. exists () {outputImage. delete ();} outputImage. createNewFile ();} catch (IOException e) {e. printStackTrace ();} // convert the File object to Uri and start the camera program imageUri = Uri. fromFile (outputImage); Intent intent = new Intent (android. media. action. IMAGE_CAPTURE); // specifies the image intent. putExtra (MediaStore. EXTRA_OUTPUT, imageUri); // specify the output address of the image startActivityForResult (intent, TAKE_PHOTO); // start the camera // return the onActivityResult () function after taking the photo startActivityForResult }}); if (savedInstanceState = null) {getFragmentManager (). beginTransaction (). add (R. id. container, new PlaceholderFragment ()). commit ();}}
You can use the startActivityForResult and onActivityResult methods to take and save a photo:

 

Protected void onActivityResult (int requestCode, int resultCode, Intent data) {super. onActivityResult (requestCode, resultCode, data); if (resultCode! = RESULT_ OK) {Toast. makeText (MainActivity. this, ActivityResult resultCode error, Toast. LENGTH_SHORT ). show (); return;} switch (requestCode) {case TAKE_PHOTO: Intent intent = new Intent (com. android. camera. action. CROP); // CROP intent. setDataAndType (imageUri, image/*); intent. putExtra (scale, true); // sets the intent width to a high ratio. putExtra (aspectX, 1); intent. putExtra (aspectY, 1); // you can specify the width and height of the cropped image. putExtra (outputx, 340); intent. putExtra (outputY, 340); intent. putExtra (MediaStore. EXTRA_OUTPUT, imageUri); Toast. makeText (MainActivity. this: crop the image, Toast. LENGTH_SHORT ). show (); // broadcast refresh album Intent intentBc = new Intent (Intent. ACTION_MEDIA_SCANNER_SCAN_FILE); intentBc. setData (imageUri); this. sendBroadcast (intentBc); startActivityForResult (intent, CROP_PHOTO); // set the cropping parameter to display the image to ImageViewbreak; case CROP_PHOTO: try {// The image is parsed into a Bitmap object Bitmap = BitmapFactory. decodeStream (getContentResolver (). openInputStream (imageUri); Toast. makeText (MainActivity. this, imageUri. toString (), Toast. LENGTH_SHORT ). show (); showImage. setImageBitmap (bitmap); // display the cropped photo} catch (FileNotFoundException e) {e. printStackTrace ();} break; default: break ;}}

Because it involves data writing and Camera operations on the SD card, you need to declare the permission in the AndroidMainfest. xml file:

 

 
   
  
 
Shows the running result:

 

 

Pay attention to the following issues:
1. photographing and interaction between startActivityForResult and onActivityResult are involved.

 

StartActivityForResult (Intent intent, // Intent object int requestCode //> = 0 when Activity ends, requestCode will be returned in onActivityResult () onActivityResult (int requestCode, // provided to onActivityResult, to confirm the returned data from the int resultCode returned by the Activity, // The Child Activity usually returns RESULT_CANCELED or RESULT_OKIntent data through its setResult () method. // an Intent object with the returned data)

Here, the requestCode of onActivityResult corresponds to the requestCode in startActivityForResult. At the same time, photos are taken and taken based on the Intent intent. The core code is as follows: (the parameter setting of Intent is omitted)
Intent intent = new Intent (android. media. action. IMAGE_CAPTURE );
StartActivityForResult (intent, TAKE_PHOTO );
Intent intent = new Intent (com. android. camera. action. CROP );
StartActivityForResult (intent, CROP_PHOTO );
2. Use Android to save the photo in the system album. The latest photo cannot be displayed immediately in the Image Library.The solution is to send the built-in broadcast to refresh the album for display. The Code is as follows:

Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);intentBc.setData(imageUri);     this.sendBroadcast(intentBc);    

You may use the following broadcast to scan the entire SD card, but 4.4 does not allow this operation:
SendBroadcast (new Intent (Intent. ACTION_MEDIA_MOUNTED, Uri. parse (...)))
Reference http://blog.csdn.net/xiaanming/article/details/8990627
3. when a program is running, it may find that the result image is very small. When triggered by an Intent, the Camera program will not return the full-size image to the main tune activity, which requires a large amount of memory, the memory size of mobile devices is limited. normally, Camera returns a very small thumbnail in the returned intent. A large image may cause OOM problems. reference: Android multimedia development advanced programming: Shawn Van Every
Provides the BitmapFactory class for large image Android, allowing Bitmap images to be loaded through various resources. call BitmapFactory. the Options class defines how to read Bitmap into the memory. When loading an image, you can set the BitmapFactory sampling size. specify the inSampleSize parameter to indicate the proportion of the Bitmap image during loading. if inSampleSize = 8, an image with a size of 1/8 of the original image is generated. refer to the following code:

If (resultCode = RESULT_ OK) {DisplayMetrics dm = new DisplayMetrics (); getWindowManager (). getdefadisplay display (). getMetrics (dm); int width = dm. widthPixels; // The width of int height = dm. heightPixels; // height // load the image size instead of BitmapFactory. options BMP factoryoptions = new BitmapFactory. options (); BMP factoryoptions. inJustDecodeBounds = true; // If bitmap is null, only the image width and height are put in Options int heightRatio = (int) Math. ceil (BMP factoryoptions. outHeight/(float) height); int widthRatio = (int) Math. ceil (BMP factoryoptions. outWidth/(float) width); // sets the image compression ratio. if the two ratios are greater than 1, the image will be greater than the screen if (heightRatio> 1 & widthRatio> 1) {if (heightRatio> widthRatio) {BMP factoryoptions. inSampleSize = heightRatio;} else {BMP factoryoptions. inSampleSize = widthRatio ;}// the image is actually decoded by BMP factoryoptions. inJustDecodeBounds = false; Bitmap bitmap = BitmapFactory. decodeFile (imageUri. toString (), BMP factoryoptions); showImage. setImageBitmap (bitmap); // display the cropped photo}

4. After cropping Images Using nexus 4, setImageBitmap cannot be displayed in the ImageView control. Only the Save button and no cropping button are displayed. The RESULT_ OK is not returned in the test. This problem cannot be solved. Why?
Reference: Unable to Save Photo Edits
Finally, I hope the article will be helpful to you. This is the basic article and Solution Process for studying Android image processing.

References and recommended blog posts: (both are very good materials -.-)
The first line of Android code: Guo Lin, referring to 8.3 calling cameras and photo albums
Android photo image selection and image cropping By: Lee_Allen
Android _ Camera _ call the System Camera to return data blank By: strawberry2013
Detailed description of Android image cropping function By: Pony
Photo Taking and photo saving in image sets for Android
Android photos are taken and displayed in ImageView (advanced) By: leesa
Android mobilizes the camera and displays the photo on ImageView.
Cameraintent data null in onActivityResult (int requestCode, int resultCode, Intentdata)
Android can efficiently load large charts and multi-graph solutions to effectively avoid program OOM By: guolin
Android camera and album get the image and save it to the SD card By: Tang Ren _ Ryan
Android: obtain local images | directly obtain the photo image By: zcljy0318

 

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.