Android photo or gallery Select image upload after compression

Source: Internet
Author: User

Record the implementation process by taking pictures or selecting images from albums by compressing and uploading many of the common functions of the application

A: Create a temporary folder to save the compressed image you need to upload

        /** * Path: Store picture directory path */private String path = Environment.getexternalstoragedirectory (). GetPath () + "/xxx/";/** * savecatal OG: Save files directory */private file savecatalog;/** * SaveFile: Saved files */private file saveFile;        public string Createorgetfilepath (string fileName, Context mcontext) {savecatalog = new File (path); Savecatalog.exists ()) {savecatalog.mkdirs ();} SaveFile = new File (Savecatalog, fileName); try {savefile.createnewfile ();} catch (IOException e) {Toast.maketext ( Mcontext, "Failed to create file, please check if SD has enough space", Toast.length_short). Show (); E.printstacktrace ();} return Savefile.getabsolutepath ();}

Two: Choose the way to get pictures via the dialog box (photo or photo album) <string-array name= "Get_image_way" >

<item > Photo </item> <item > Albums </item> </string-array>
Private string[] Image;image = Getresources (). Getstringarray (R.array.get_image_way);/** * TODO get photos by photo or Atlas * @author { Author Wangxiaohong} */private void Selectimage () {//TODO auto-generated method stubstring state = Environment.getexterna Lstoragestate (); if (!state.equals (environment.media_mounted)) {Util.showtoast (this, getresources (). GetString ( R.STRING.CHECK_SD)); Check that the SD card is available for return;} Alertdialog.builder Builder = new Alertdialog.builder (this), Builder.settitle (r.string.pick_image). Setitems (Image, New Dialoginterface.onclicklistener () {public void OnClick (Dialoginterface dialog, int which) {if (Image[which].equals ( GetString (R.string.my_data_image_way_photo)) {Getimagebyphoto ();} else {getimagebygallery ();}}); Builder.create (). Show ();

private void Getimagebygallery () {Intent Intent = new Intent (Intent.action_pick, MediaStore.Images.Media.EXTERNAL_ Content_uri); Intent.settype ("image/*"); Startactivityforresult (Intent, image_result);}

public string GetPath (string Carid, String fileName, Context mcontext) {file Savecatalog = new File (Constant.cache, Carid) ;//Savecatalog = new File (path); if (!savecatalog.exists ()) {savecatalog.mkdirs ();} SaveFile = new File (Savecatalog, fileName); try {savefile.createnewfile ();} catch (IOException e) {Toast.maketext ( Mcontext, "Failed to create file, please check if SD has enough space", Toast.length_short). Show (); E.printstacktrace ();} return Savefile.getabsolutepath ();}

  

private void Getimagebyphoto () {
public static final String CACHE = Environment.getexternalstoragedirectory (). GetAbsolutePath ()+ "/pinchebang/ ";
Path = Util.getpath (User.getcar (). Getcarid () + "", Mphotoname, personalinfoactivity.this); Imageuri = Uri.fromfile (new File (path), Intent Intent = new Intent ("Android.media.action.IMAGE_CAPTURE"); Intent.putextra (Mediastore.extra_ OUTPUT, Imageuri); Startactivityforresult (Intent, camera_result);}

Three: The picture that gets in Onactivityresult does compress processing

@Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {//TODO auto-generated method stub Super.onactivityresult (Requestcode, ResultCode, data); if (resultcode! = ACTIVITY.RESULT_OK) return; Bitmap Bitmap = null;if (Requestcode = = Camera_result) {Bitmap = Util.getsmallbitmap (personalinfoactivity.this, path); Boolean flag = Util.save (personalinfoactivity.this, Path, bitmap);} else if (Requestcode = = Image_result) {Uri selectedimage = data.getdata ();p ath = Util.getimagepath ( Personalinfoactivity.this, selectedimage); bitmap = Util.getsmallbitmap (personalinfoactivity.this, path); String pcbpathstring = Util.getpath (User.getcar (). Getcarid () + "", mphotoname,personalinfoactivity.this);; Util.save (Personalinfoactivity.this, pcbpathstring, bitmap);p ath = pcbpathstring;} if (null! = Bitmap) {mypicture.setimagebitmap (bitmap); Httputil.uploadfile (personalinfoactivity.this, Path, "userimg", constant.url_verify_driver);//MemoryCache MemoryCache = new MemoryCache ();//MEMORYCAche.put (URL, bitmap);}} 
The corresponding compression method above

/** * TODO filePath: Picture Path * * @author {author Wangxiaohong} */public Bitmap Getsmallbitmap (Context mcontext, String Filepa Th) {Displaymetrics dm;dm = new Displaymetrics ();((Activity) mcontext). Getwindowmanager (). Getdefaultdisplay (). Getmetrics (DM); final bitmapfactory.options Options = new Bitmapfactory.options (); options.injustdecodebounds = true; Bitmapfactory.decodefile (FilePath, options);//Calculate insamplesizeoptions.insamplesize = Calculateinsamplesize ( Options, Dm.widthpixels, dm.heightpixels);//Decode bitmap with insamplesize setoptions.injustdecodebounds = false; Return Bitmapfactory.decodefile (FilePath, options);} public int calculateinsamplesize (bitmapfactory.options Options, int reqwidth, int reqheight) {//Raw height and width of i magefinal int height = options.outheight;final int width = Options.outwidth;int insamplesize = 1;if (Height > reqheight || Width > Reqwidth) {//Calculate ratios of height and width to requested height and//widthfinal int heightratio = Math. Round (float) height/(float) reqheight), final int widthRatio = Math.Round ((float) width/(float) reqwidth);//Choose the Smallest ratio as insamplesize value, this will//guarantee//a final image with both dimensions larger than or equal to T he//requested height and width.insamplesize = HeightRatio < WidthRatio? Heightratio:widthratio;} return insamplesize;} /** * TODO Save and compress the picture to save bitmap to the path path of the file * * @author {author Wangxiaohong} */public boolean Save (Context Mcontext, Str ing path, Bitmap Bitmap) {displaymetrics DM;DM = new Displaymetrics ();((Activity) mcontext). Getwindowmanager (). Getdefaultdisplay (). Getmetrics (DM), if (path! = null) {try {//Filecache Filecache = new Filecache (mcontext);//File F = fi Lecache.getfile (URL); File F = new file (path); FileOutputStream fos = new FileOutputStream (f); bitmap.compress (Bitmap.CompressFormat.JPEG, N, Fos); Savemybitmap ( bitmap); return true;} catch (Exception e) {return false;}} else {return false;}} private void Savemybitmap (Bitmap bm) {FIleoutputstream FOut = null;try {fOut = new FileOutputStream (saveFile);} catch (FileNotFoundException e) {E.printstacktra CE ();} Bm.compress (Bitmap.CompressFormat.JPEG, D, FOut); try {Fout.flush ();} catch (IOException e) {e.printstacktrace ();} try {fout.close ();} catch (IOException e) {e.printstacktrace ();}} public string GetPath (string Carid, String fileName, Context mcontext) {file Savecatalog = new File (Constant.cache, Carid) ;//Savecatalog = new File (path); if (!savecatalog.exists ()) {savecatalog.mkdirs ();} SaveFile = new File (Savecatalog, fileName); try {savefile.createnewfile ();} catch (IOException e) {Toast.maketext ( Mcontext, "Failed to create file, please check if SD has enough space", Toast.length_short). Show (); E.printstacktrace ();} return Savefile.getabsolutepath ();} /** * TODO get photo Album Select Picture Path * * @author {author Wangxiaohong} */public String Getimagepath (Context mcontext, Uri Contenturi) {string[] proj = {MediaStore.Images.Media.DATA}; cursor cursor = mcontext.getcontentresolver (). Query (Contenturi, proj, NULL, NULL, NULL); int column_index = Cursor.getcolumnindexorthrow (MediaStore.Images.Media.DATA); Cursor.movetofirst (); String ImagePath = cursor.getstring (Column_index); Cursor.close (); return ImagePath;}

Four: Upload

public static void UploadFile (Context mcontext, string path, string modelvalue, string url) {New Photouploadasynctask (MCon Text). Execute (path, modelvalue, URL);} Class Photouploadasynctask extends Asynctask<string, Integer, string> {//private String URL = "http://192.168.83.2 13/receive_file.php ";p rivate context Context;public Photouploadasynctask (context context) {This.context = context;} @Overrideprotected void OnPreExecute () {} @SuppressWarnings ("deprecation") @Overrideprotected String Doinbackground ( String ... params) {//save required to upload file information Multipartentitybuilder entitys = Multipartentitybuilder.create (); Entitys.setmode ( httpmultipartmode.browser_compatible); Entitys.setcharset (Charset.forname (HTTP. Utf_8)); File File = new file (Params[0]), Entitys.addpart ("image", new Filebody (file)), Entitys.addtextbody ("model", params[1]); Httpentity httpentity = Entitys.build (); return Httputil.uploadfilewithpost (params[2], context, httpentity);} @Overrideprotected void Onprogressupdate (Integer ... progress) {} @Overrideprotected void OnPostExecute (String result) {Toast.maketext (context, result, toast.length_short). Show ();}} /** * for File upload * * @param URL * @param mcontext * @param entity * @return */@SuppressWarnings ("deprecation") public static S Tring uploadfilewithpost (String URL, Context mcontext, httpentity entity) {Util.printlog ("start upload"); try {setTimeout (); Httpclient.getparams (). Setparameter (coreprotocolpnames.protocol_version,httpversion.http_1_1);//Set connection time-out// Httpclient.getparams (). Setparameter (coreconnectionpnames.connection_timeout,//5000); HttpPost uppost = new HttpPost (URL); uppost.setentity (entity); HttpResponse HttpResponse = Httpclient.execute (Uppost, HttpContext), if (Httpresponse.getstatusline (). GetStatusCode ( ) = = HTTPSTATUS.SC_OK) {return mcontext.getstring (r.string.upload_success);}} catch (Exception e) {util.printlog ("upload error"); E.printstacktrace ();} finally {//if (httpClient! = null && httpclient.getconnectionmanager () = null)//{//Httpclient.getconnection Manager (). Shutdown();//}//}util.printlog ("Upload succeeded"); return mcontext.getstring (R.string.upload_fail);} 

  

Android photo or gallery Select image upload after compression

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.