Call system camera, album feature

Source: Internet
Author: User
Tags dateformat

The first idea is that this piece of functionality goes out alone;

Or integration might work better in the activity,

And Samsung's phone call system camera will cause the call activity will restart the life cycle, if it is called in the fragment, will encounter more problems, do outsourcing injury, want to go into this problem is not time, temporarily recorded in the activity to solve the problem of the method, Easy to use when used in the back.

For example, click on a button in the activity, pop up a dialog box, choose to take pictures or choose a picture

Mbutton.setonclicklistener (New onclicklistener ()  {     @Override       public void onclick (VIEW V)  {      final  CharSequence[] items = {  "Photo Album",  "Photo",  "Cancel"  };      dlg = new alertdialog.builder (renzhengzpactivity.this)           .settitle ("select Picture")          .setitems (   items,                       new dialoginterface.onclicklistener ()  {                            public void onclick ( DialogInterface dialog, int  Item)  {                              //  here item is based on the chosen way,                               //  in the items array is defined in two ways, the picture is labeled 1, so call the camera method                                 if  (item == 1)  {                                    togetpic ();                                 } else if  (item == 0)  {                                    totakephoto ();                                 } else if  (item == 2)  {                                     dlg.dismiss ();                                 }                            }                         }                    ). Create ();        dlg.show ();       }   });


2 ways to jump to a system camera and system album in activity
/** jump to album */private Void Totakephoto () {Intent getImage = new Intent (intent.action_get_content); Getimage.addcategory ( intent.category_openable); Getimage.settype ("Image/jpeg"); Startactivityforresult (GetImage, 1);} /** jumps to the system camera, specifying the location of the saved photo picture */private void Togetpic () {Intent Intent = new Intent (mediastore.action_image_capture);// The following sentence specifies the path to the photo storage after the camera is called Intent.putextra (Mediastore.extra_output, Uri.fromfile (new File) ( Environment.getexternalstoragedirectory (), "xiaoma.jpg")); Startactivityforresult (Intent, 2);}


Onactivityresult Methods for replication activity:

@Overridepublic void Onactivityresult (int requestcode, int resultcode, Intent data) {switch (Requestcode) {//) If you are getting C directly from the album ASE 1:log.i (TAG, "album Gets the picture back to renzhengzpactivity and starts cropping"); if (data! = null) {Startphotozoom (Data.getdata ());} break;//if the camera is called to take a photo when case 2:log.i (TAG, "Call the camera to take pictures to get the picture back to Renzhengzpactivity, and start cropping"); File temp = new file (environment.getexternalstoragedirectory () + "/xiaoma.jpg"); Startphotozoom (Uri.fromfile (temp)); break;//get the cropped picture case 3:log.i (TAG, "after cropping the picture, get the picture path and add to the collection"); if (data = null) {Setpictoview (data);} Break;default:break;} Super.onactivityresult (Requestcode, ResultCode, data);}

To invoke the cropping function of the system:

/** * Cropping image method Implementation * * @param uri */public void Startphotozoom (Uri uri) {Intent Intent = new Intent ("Com.android.camera.actio N.crop "); Intent.setdataandtype (URI," image/* ");//The following crop=true is set to set the display in the intent of the open view can be clipped Intent.putextra (" CROP ", "true");//Aspectx aspecty is a proportional Intent.putextra ("Aspectx", 1); Intent.putextra ("Aspecty", 1);//Outputx Outputy is the cropped image width height intent.putextra ("Outputx"), Intent.putextra ("Outputy", "Intent.putextra"); Startactivityforresult (Intent, 3);}

Save the picture after it has been cropped

/** * Save image data after cropping * * @param picdata */private void Setpictoview (Intent picdata) {Bundle extras = Picdata.getextras (); if (Extras! = null) {photo = Extras.getparcelable ("data");//write to SD card, photo is a stream of data: Create a folder to write to the SD card, create a collection, save all the picture path//3. Write to the SD card and get the path, Pass the string path = Environment.getexternalstoragedirectory () + "/project/"; String photoname = Tools.createfilename ();//save bitmap as file path to SD card Tools.savephototosdcard (path, photoname, photo); LOG.I (TAG, "The path name of the Photo:" + path + "/" + photoname);//todo to hit the path after the photo}}

Methods in Tools:

/** *   get the current time to name different files   *   @return  */public static string createfilename ()  {    string  fileName =  "";     date date = new date ( System.currenttimemillis ()); //  system Current Time     SimpleDateFormat dateFormat  = new simpledateformat (             "' IMG ' _yyyymmdd_hhmmss ');     filename = dateformat.format (date)  +  ". jpg";      return filename;} 
 /**  *    Save the bitmap  as a file path to the SD card and use the file path directly when it is removed.   *    get the file path can be file file = new file (file path), then you can put this file upload server     *  @param  path  *  @param  photoName  *  @param   Photobitmap  */ public static void savephototosdcard (String path,  string photoname,            bitmap  Photobitmap)  {        if  ( Android.os.Environment.getExternalStorageState (). Equals (                 android.os.environment.media_mounted))  {             file dir = new file (PATH);             if  (!dir.exists ()) &NBsp {                dir.mkdirs ();             }             file photofile = new file (Path, photoName);  Creates a file under the specified path             system.out.println ( Photofile);            fileoutputstream  Fileoutputstream = null;            try  {                 Fileoutputstream = new fileoutputstream (Photofile);                 system.out.println (photofile+ " ....    &n................ ";");bsp;            if  (photoBitmap !=  NULL)  {                     if  (Photobitmap.compress (bitmap.compressformat.png, 100,                              fileoutputstream))  {                          Fileoutputstream.flush ();                     }                 }            } catch   (FileNotFoundException e)  {                 photofile.delete ();                 e.printstacktrace ();             }  catch  (ioexception e)  {                 photofile.delete ();                 e.printstacktrace ();             } finally {                 try {                     if (fileoutputstream!=null) {                         fileoutputstream.close ();                      }                }  catch  (ioexception e)  {                     e.printstacktrace ();                 }                 photobitmap.recycle ();             }        }     }


In addition, in the call system after the photo or photo album, if you do not need to call the crop, you can also get Intent.getdata (), you can get the image in the Android system URI, you can also get the picture by URI

/** *  in activity  's  onactivityresult ()     This method,   if the photo is selected from the album,   *  Call this method,  get the path to the photo  *  @param  activity *  @param  data * @ Return */public static string loadimgfromgallery (activity activity, intent  Data)  {if (data == null) {return null;} if  (Bitmap != null)  {bitmap.recycle ();}   External Program Access ContentProvider provides data   can be accessed via Contentresolver interface contentresolver resolver =  Activity.getcontentresolver ();//  here to determine if the activity is the one you want try {uri originaluri =  Data.getdata (); //  Gets the picture uri//  appears to bitmap picture//todobitmap bitmap = getthumbnail (Uri  uri,int size);//  Here begins the second part, gets the path of the picture:string[] proj = {  mediastore.images.media.data };//  seems to be the encapsulation interface of Android Multimedia database, the specific look of Android document cursor cursor =  Activity.managedquery (originaluri, Proj, null, null, null);//  According to my own understanding   This is the index value of the image to get the user's choice int column_index =  Cursor.getcolumnindexorthrow (MediaStore.Images.Media.DATA);//  move the cursor to the beginning   Carelessness can easily lead to cross-border Cursor.movetofirst (); return cursor.getstring (Column_index);}  catch  (ioexception e)  {e.printstacktrace ();} Return null;}

Take the image bitmap object by URI

(method Source: http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/0826/1665.html)

/*** size  width and height max */public static bitmap getthumbnail (uri uri,int size)  throws filenotfoundexception, ioexception{    //to input stream via URI      inputstream input = this.getcontentresolver (). Openinputstream (URI);      //get the Option object,  set some optimized properties     BitmapFactory.Options  Onlyboundsoptions = new bitmapfactory.options ();     Onlyboundsoptions.injustdecodebounds = true;    onlyboundsoptions.indither=true ;//optional    onlyboundsoptions.inpreferredconfig=bitmap.config.argb_8888;//optional     bitmapfactory.decodestream (input, null, onlyboundsoptions);//decode the image from the input stream, Get the picture of Option    input.close ();//Close input stream     if  (( onlyboundsoptions.outwidth == -1)  | |   (Onlyboundsoptions.outheight == -1)) {        return null;    }     int originalSize =  (onlyboundsoptions.outheight >  Onlyboundsoptions.outwidth)  ? onlyboundsoptions.outheight : onlyboundsoptions.outwidth;// The maximum value of the     //gets the ratio of the given size and the original size     double ratio =  ( originalsize > size)  ?  (originalsize / size)  : 1.0;     bitmapfactory.options bitmapoptions = new bitmapfactory.options ();     bitmapoptions.insamplesize = getpoweroftwoforsampleratio (ratio);     bitmapoptions.indither=true;//optional    bitmapoptions.inpreferredconfig= Bitmap.config.argb_8888;//optional    input = this.getcontentresolver (). Openinputstream (URI);//Get input stream     //again based on shrinkingoption to get Bitmap    bitmap bitmap = bitmapfactory.decodestream (input,  null, bitmapoptions);     input.close ();    return  Bitmap;} Private static int getpoweroftwoforsampleratio (double ratio) {    int  k = integer.highestonebit ((int) Math.floor (ratio));     if (k==0)  return  1;    else return k;}


When the photo is returned, because the address of the saved photo has been established, it is OK to get the picture directly from the address under the SD card.

How to get pictures by address

/** * Load local image, thumbnail * @param imgpath * @return */public static Bitmap getloacalbitmap (String imgpath) {bitmapfactory.options options = new Bitmapfactory.options (); options.inpreferredconfig = Bitmap.config.argb_8888;options.inpurgeable = True ; options.ininputshareable = true; FileInputStream fis = null;try {fis = new FileInputStream (Imgpath);} catch (IOException e) {e.printstacktrace ();} Return Bitmapfactory.decodestream (FIS, NULL, options);}


Another well-written call to the System Camera Blog: (worship)

http://blog.csdn.net/a497393102/article/details/8949727

Call system camera, album feature

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.