Lecture 3 ------- select an image from the system (take a photo or take it from the album)

Source: Internet
Author: User

Retrieving images from the system is a very common function for Android writing. However, it is quite troublesome to write images every time.

Next I will introduce a encapsulated class I wrote.

From the above, the function is very clear. Click the get image button to display a translucent interface. You can use the camera to take pictures and select two ways to obtain images from the album.

Go directly to the code

Package COM. yixuan; import Java. io. file; import Java. io. filenotfoundexception; import Java. io. fileoutputstream; import Java. io. ioexception; import COM. example. handlertest. r; import android. app. activity; import android. content. context; import android. content. intent; import android. graphics. bitmap; import android. graphics. bitmapfactory; import android.net. uri; import android. OS. bundle; import android. OS. environme NT; import android. provider. mediastore; import android. util. displaymetrics; import android. view. view; import android. view. view. onclicklistener; import android. widget. toast;/***** <p> * Description: it is difficult to use the onresult * method of activity because many times photos are obtained from fragment, set a variable in a static class to store the obtained image path ** <p> * Creator: ztt * </P> * <p> * Creation Time: 1:45:21 * </P> */public abstract class pickphotoactivity extends activity implementso Nclicklistener {/* callback type returned by activity */public static final int photo_picked_with_gallery = 9001; public static final int photo_picked_with_camera = 9002; public static final int croped_photo = 9003; private Final int cropwidth = 160; private final int cropheight = 160; private Activity Act; private Boolean docrop = true; protected int width; protected int height; protected int default_width = 480; protected I NT default_height = 480; protected context CTX; private int DPI; private int screenwidth; protected static string picpath;/* obtain the image path */@ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_pick_photo); CTX = This; intent = getintent (); displaymetrics metric = new displaymetrics (); getwindowmanager (). getdefadisplay display (). getme Trics (metric); float density = metric. density; DPI = (INT) (metric. densitydpi * density); default_width = metric. widthpixels; default_height = metric. heightpixels; // string Path = intent. getstringextra ("temppath"); docrop = intent. getbooleanextra ("docrop", true); width = intent. getintextra ("width", default_width); Height = intent. getintextra ("height", default_height); file picturepathfile = new file (getpi Cpath (); If (! Picturepathfile. exists () {picturepathfile. mkdirs ();} screenwidth = metric. widthpixels; // default_width = getscale () * 2; // default_height = getscale () * 2; system. out. println (getscale () * 2); initview ();} private int getscale () {double val = 4D * DPI/screenwidth; val = Val * 100d; return Val. intvalue ();} private void initview () {findviewbyid (R. id. pick_photo_from_camera ). setonclicklistener (this); findvie Wbyid (R. id. pick_photo_from_gallery ). setonclicklistener (this); findviewbyid (R. id. cancel ). setonclicklistener (this); Act = This ;}@ overrideprotected void onactivityresult (INT requestcode, int resultcode, intent data) {super. onactivityresult (requestcode, resultcode, data); If (resultcode = result_ OK) {Switch (requestcode) {case when: If (docrop) {docropphoto (new file (getfullpath ()), cr Opwidth, cropheight);} else {savepicture (picpath, null);} break; Case photo_picked_with_gallery: picpath = getpathfromuri (data. getdata (). tostring (); If (docrop) {docropphoto (new file (picpath), cropwidth, cropheight);} else {savepicture (picpath, null);} break; Case croped_photo: bitmap IMG = data. getparcelableextra ("data"); // imagetools. savephototosdcard (IMG, getpicpath (), // gettempimagename (); savepictu Re (null, IMG); break; default: Break ;}} else {clearfullpath () ;}} public static void clearfullpath () {picpath = NULL;} Public String getpicpath () {return environment. getexternalstoragedirectory (). tostring () + "/";} private void savepicture (string picturepath, Bitmap bitmap) {bitmap photo = NULL; try {If (Bitmap = NULL) {photo = decodebitmap (picturepath, width, height);} else {photo = bitmap;} savepictrue (Photo); If (photo! = NULL &&! Photo. isrecycled () {photo. recycle ();} picpath = getpicpath () + gettempimagename (); aftersavephoto (getfullpath (); file = new file (getfullpath (); If (file. exists () {file. delete () ;}} catch (exception e) {e. printstacktrace () ;}} public static string getfullpath () {return picpath;} protected abstract void aftersavephoto (string picpath); Private void savepictrue (Bitmap newbitmap) {savephototosdcard (newbi TMAP, getpicpath (), gettempimagename ();} public static void savephototosdcard (Bitmap photobitmap, string path, string photoname) {If (checksdcardavailable ()) {file dir = new file (PATH); If (! Dir. exists () {dir. mkdirs ();} file photofile = new file (path, photoname); fileoutputstream = NULL; try {fileoutputstream = new fileoutputstream (photofile); 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 {fileoutputstream. close (); photobitmap. recycle ();} catch (ioexception e) {e. printstacktrace () ;}}}@ overridepublic void onclick (view v) {I F (v. GETID () = R. id. pick_photo_from_camera) {takepickture ();} else if (v. GETID () = R. id. pick_photo_from_gallery) {getpickturefromgallery () ;}else {finish () ;}// switch (v. GETID () {// case R. id. pick_photo_from_camera: // break; //} // switch (v. GETID () {// case R. id. pick_photo_from_camera: // takepickture (); // break; // case R. id. pick_photo_from_gallery: // getpickturefromgallery (); // break; // case R. I D. cancel: // finish (); // break; //} public static Boolean checksdcardavailable () {return android. OS. environment. getexternalstoragestate (). equals (Android. OS. environment. media_mounted);} private void getpickturefromgallery () {intent openalbumintent = new intent (intent. action_pick); openalbumintent. settype ("image/*"); startactivityforresult (openalbumintent, photo_picked_with_gallery);} private void takepi Ckture () {intent opencameraintent = new intent (mediastore. action_image_capture); picpath = getpicpath () + gettempimagename (); Uri imageuri = Uri. fromfile (new file (picpath); opencameraintent. putextra (mediastore. extra_output, imageuri); If (docrop) {opencameraintent. putextra ("Return-Data", true);} startactivityforresult (opencameraintent, photo_picked_with_camera);} protected static string gettempimagenam E () {return "IMG _" + "Temp" + ". PNG "; // return fileutil. gettemppath () + appconstants. default_pic_name;} @ suppresswarnings ("deprecation") Public String getpathfromuri (string stringextra) {URI uri = Uri. parse (stringextra); string [] proj = {mediastore. images. media. data}; android. database. cursor actualimagecursor = pickphotoactivity. this. managedquery (Uri, proj, null); int actual_image_column _ Index = actualimagecursor. getcolumnindexorthrow (mediastore. images. media. data); actualimagecursor. movetofirst (); string img_path = actualimagecursor. getstring (actual_image_column_index); Return img_path;} public bitmap decodebitmap (string path, int width, int height) {bitmapfactory. options = new bitmapfactory. options (); options. injustdecodebounds = true; // obtain the image width and height through this Bitmap bitmap = bitm Apfactory. decodefile (path, options); If (Bitmap = NULL) {system. out. println ("bitmap is empty");} float realwidth = options. outwidth; float realheight = options. outheight; system. out. println ("Real Image Height:" + realheight + "width:" + realwidth); int scale = math. max (INT) (realwidth/width), (INT) (realheight/height); If (scale <= 1) {scale = 1;} options. insamplesize = scale; options. injustdecodebounds = false; // pay attention to this Set options. injustdecodebounds to false. The image will be read this time. // Bitmap = bitmapfactory. decodefile (path, options); int W = bitmap. getwidth (); int H = bitmap. getheight (); system. out. println ("thumbnail Height:" + H + "width:" + W); Return bitmap;} private void docropphoto (file F, int outwith, int outheight) {try {// start gallery to edit the final intent = getcropimageintent (URI. fromfile (F), outwith, outheight); If (act! = NULL) Act. startactivityforresult (intent, croped_photo); elseact. startactivityforresult (intent, croped_photo);} catch (exception e) {toast. maketext (Act, Act. getstring (R. string. get_picture_failed), toast. length_long ). show () ;}} private intent getcropimageintent (URI photouri, int cropwidth, int cropheight) {intent = new intent ("com. android. camera. action. crop "). setdataandtype (photouri, "image /*"). putextra ("crop", "true "). putextra ("Return-Data", true); intent. putextra ("aspectx", cropwidth); intent. putextra ("aspecty", cropheight); intent. putextra ("outputx", cropwidth); intent. putextra ("outputy", cropheight); Return intent ;}}


This class is very long, and many people may not want to see it. If you think the interface is still compatible, use it directly. How can I use it next?

This class is an abstract class with the abstract method aftersavephoto (string picpath). This method is executed after the image is selected, and picpath is the position of the selected image. So if you want to use it, you only need to write a class and implement this method, and you can select the image to do in the method.

Calling this class is also very simple, as shown below

/*** Cropping not required */private void takephoto () {intent = new intent (this, phototestacticity. class); intent. putextra ("docrop", false); this. startactivity (intent);}/*** crop the selected image */private void takephotocrop () {intent = new intent (this, phototestacticity. class); this. startactivity (intent );}

When cropping is not required, the docrop variable is passed through the bundle of intent, so no cropping is required.


Summary: there are many examples on the Internet, but you are welcome to use them if they are convenient.

Address: http://download.csdn.net/detail/u010047390/8469665




Lecture 3 ------- select an image from the system (take a photo or take it from the album)

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.