Android photos and get photo albums _android

Source: Internet
Author: User

Before encountered a variety of photos ah, get photo albums and so on, are directly to the Niang, or before the code copied, not well summed up.

No longer ask the Niang, no longer a pile of blogs to find Ah ...

----------------------------------------------I am the text of the split line-----------------------------------------------------------

One by one, first of all, call the phone camera to take photos (simplest version):

 Camerabutton.setonclicklistener (New View.onclicklistener () {
 @Override public
 void OnClick (View v) {
  Intent intent=new Intent (mediastore.action_image_capture);
  Startactivityforresult (Intent,take_photo);
 }
);

protected void Onactivityresult (int requestcode, int resultcode, Intent data) {
 Super.onactivityresult (requestcode , ResultCode, data);
 if (RESULTCODE==RESULT_OK) {
  Bundle bundle=data.getextras ();
  Bitmap bitmap= (Bitmap) bundle.get ("Data");
  Photoimageview.setimagebitmap (bitmap);
 }


This method is simple, but the resulting picture is a thumbnail, usually very vague, many times does not meet our requirements, we need to get photos of the original image.

And usually want to get the original image of the method, we will first customize the picture name, confirm the image storage location, and then according to the image location of the URI, nature can get the original bitmap. code such as  

 /** * Custom picture name, get photo of File/private file Createimgfile () {//determine filename String filename= "Img_" +new simpledateformat ("yy
Yymmdd_hhmmss "). Format (new Date ()) +". jpg ";
File Dir=getexternalfilesdir (environment.directory_pictures);
File dir=environment.getexternalstoragepublicdirectory (environment.directory_pictures);
  File dir=environment.getexternalstoragedirectory ();
  File dir; if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {dir=
  Environment.getexternalstoragedirectory ();
  }else{Dir=getexternalfilesdir (environment.directory_pictures);
  } file Tempfile=new file (dir,filename);
   try{if (tempfile.exists ()) {tempfile.delete ();
  } tempfile.createnewfile ();
  }catch (IOException e) {e.printstacktrace ();
  //Get the file path Photopath=tempfile.getabsolutepath ();
 return tempfile;
   ///Photo Camerabutton.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) { Just added a URI as an address for incoming Intent inTent=new Intent (mediastore.action_image_capture);
   File Photofile=createimgfile ();
   Photouri=uri.fromfile (Photofile);
   Intent.putextra (Mediastore.extra_output,photouri);
  Startactivityforresult (Intent,take_photo);
 }
 });

The code should be very clear, we defined the name of the picture, the URI passed in, so we can get the URI in the Onactivityresult, then can not be directly based on the URI bitmap? For example this:
Bitmap Bitmap=mediastore.images.media.getbitmap (Getcontentresolver (), Photouri);
Photoimageview.setimagebitmap (bitmap); This is true, unfortunately, most of our mobile phone cameras are very high-definition, the photos taken out if directly loaded into the cell phone memory, I am afraid the La la la la ...

So the only thing we can think of is to start compressing the picture:

/** * Compress picture/private void Setimagebitmap () {//Get ImageView width and height int targetwidth
  =photoimageview.getwidth ();

  int Targetheight=photoimageview.getheight ();
  According to the picture path, obtains the bitmap width and the high bitmapfactory.options options=new bitmapfactory.options ();
  Options.injustdecodebounds=true;
  Bitmapfactory.decodefile (photopath,options);
  int photowidth=options.outwidth;

  int photoheight=options.outheight;
  Gets the zoom scale int insamplesize=1; if (photowidth>targetwidth| |
   photoheight>targetheight) {int widthratio=math.round ((float) photowidth/targetwidth);
   int Heightratio=math.round ((float) photoheight/targetheight);
  Insamplesize=math.min (Widthratio,heightratio);
  ///Use current options to obtain bitmap options.insamplesize=insamplesize;
  Options.injustdecodebounds=false;
  Bitmap Bitmap=bitmapfactory.decodefile (photopath,options);
 Photoimageview.setimagebitmap (bitmap); }

The above is to fetch the camera all the code, of course Write_external_storage this permission is definitely to add.

There is also a recurring thing, is that you may be photographed, the photos did not appear in the phone album in time, but need to restart the phone before appearing. In fact, we only need to send a broadcast, you can add pictures into the phone album, the code is as follows:

 Add a picture to your phone album
 private void Galleryaddpic () {
  Intent mediascanintent=new Intent (intent.action_media_scanner_ Scan_file);
  Mediascanintent.setdata (Photouri);
  This.sendbroadcast (mediascanintent);
 }

The difficulties have passed, relatively, from the album to choose Photos, simply, I believe that as long as the code will understand, do not believe you see:

 Get photos from photo album Albumbutton.setonclicklistener (new View.onclicklistener () {@Override public void OnClick (view view) {
   Intent intent=new Intent (Intent.action_pick);
   Intent intent=new Intent (intent.action_get_content);
   Intent.settype ("image/*");
  Startactivityforresult (Intent,pick_photo);
 
 }
 }); protected void Onactivityresult (int requestcode, int resultcode, Intent data) {Super.onactivityresult (Requestcode, ResU
  Ltcode, data);
     if (RESULTCODE==RESULT_OK) {switch (requestcode) {case Take_photo:setimagebitmap ();
     Galleryaddpic ();
    Break
     Case Pick_photo://data with the returned URI Photouri=data.getdata ();
     Get photo path string[] Filepathcolumn={mediastore.audio.media.data};
     Cursor cursor=getcontentresolver (). query (Photouri,filepathcolumn,null,null,null);
     Cursor.movetofirst ();
     Photopath=cursor.getstring (Cursor.getcolumnindex (filepathcolumn[0));
     Cursor.close ();
   With the photo path, after that is the compressed picture, and there is no difference between setimagebitmap ();  Break
 }
  }
 }

Quite simply, we get the URI of the selected picture from data in Onactivityresult (), and then we can get the picture path by just one step. And with the photo path, there's no problem.

The whole demo here is over, the next content can not see, demo download link: Download the address

Ask yourself the answer time:
Q:What is an SD card? Because when I created file, the catalog file was Environment.getexternalstoragedirectory () by default, and it needed to be detected before it was used. This is the Environment.getexternalstoragestate (). Equals (environment.media_mounted) that asks if the SD card is properly installed. I used a new phone and it was still installed correctly.
A : the phone has a built-in SD card, so even if I bought a new phone, but still can detect the existence of SD card.

An interesting answer is that the built-in SD card is similar to a computer hard disk, the external SD card is similar to the mobile hard drive, but also not sure whether it is correct.

Q: When you create a file, what do you mean by a few different directory files? What's the difference?

Answer: look directly at the test results, environment.getexternalstoragedirectory () address:/storage/emulated/0
Environment.getexternalstoragepublicdirectory () Address:/storage/emulated/0/pictures
Getexternalfilesdir () Address:/storage/emulated/0/android/data/com.example.notificationapp/files/pictures

Q: When you choose a photo from a photo album, there seems to be a two intent, what's the difference?

Answer: Intent intent=new Intent (Intent.action_pick);
Intent intent=new Intent (intent.action_get_content);

Both of these can actually be selected from the photo album, but what's the difference, okay, I don't get it.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.