Android Save picture to local album

Source: Internet
Author: User

I haven't written anything for a long time. Back up the knowledge. Lest I forget it.

First put a piece of code--this is a local path for Mr., save the picture to this file, and then scan the SD card. Let the system album reload under. The downside is that you can only save to DCIM.

The folder below, temporarily do not know how to obtain the path of the system camera, online looked for several methods. One of them is to read the local image and then identify the path to the local album according to certain rules.

Save, but feel that performance is not very good. Who has better ways to offer under.

 Private class Downloadtask extends Asynctask<string, Integer, string> {private context context;        Private String filepath;                 public int filelength = 0;                        Public Downloadtask (Context context) {This.context = context;            File Cachedir = new file (Imageloader.getexternalcachedir (context). GetAbsolutePath ());            if (!cachedir.exists ()) {cachedir.mkdirs (); }//filepath = imageloader.getexternalcachedir (context). GetAbsolutePath () + File.separator + "CAIHONGJIAYUAN.J            PG ";        filepath = Uiutils.generatedownloadphotopath (); } @SuppressWarnings ("resource") @Override protected string Doinbackground (String ... surl) {Powerm            Anager pm = (powermanager) context.getsystemservice (Context.power_service);            Powermanager.wakelock wl = Pm.newwakelock (Powermanager.partial_wake_lock, GetClass (). GetName ());   Wl.acquire ();         InputStream input = null;            OutputStream output = null;            HttpURLConnection connection = null;                try {URL url = new URL (surl[0]);                Connection = (httpurlconnection) url.openconnection ();                Connection.setconnecttimeout (5000);                Connection.setreadtimeout (20000);                Connection.connect (); Expect HTTP OK, so we don't mistakenly save error report//instead of the file if (c Onnection.getresponsecode ()! = HTTPURLCONNECTION.HTTP_OK) return "Server returned HTTP" + CONNECTION.G                Etresponsecode () + "" + connection.getresponsemessage ();                Filelength = Connection.getcontentlength ();                input = Connection.getinputstream ();                Output = new FileOutputStream (filepath);                byte data[] = new byte[4096];                Long total = 0; int count; while ((count = input.read (data))! =-1) {//Allow canceling with the back button if (i                    Scancelled ()) return null;                                        Total + = count;                    if (Filelength > 0)//Only if total length is known publishprogress ((int.) total);                Output.write (data, 0, count);            }} catch (Exception e) {return null;                    } finally {try {if (output! = null) output.close ();                if (input! = null) input.close (); } catch (IOException ignored) {} if (connection! = null) Connection.disc                Onnect ();            Wl.release ();        } return filepath; } @Override protected void Onprogressupdate (Integer ... values) {            TODO auto-generated Method Stub super.onprogressupdate (values);            float progress = (float) values[0]/(float) filelength; Mprogressinfo.settext (GetString (r.string.download_progress_info,stringutils.getkbunitstring (values[0)),            Stringutils.getkbunitstring (filelength));        Mprogressbar.setprogress ((int) (Progress * 100)); } @Override protected void OnPostExecute (String result) {//TODO auto-generated method s            Tub Super.onpostexecute (result);            Mdownloadview.setvisibility (View.gone); if (!            Textutils.isempty (Result)) {Imageutils.scanfile (mcurrentactivity, filepath); Toastutils.showlongtoast (Mcurrentactivity, mcurrentactivity.getstring (R.string.tips_img_save_path, filepath));}            else {toastutils.showlongtoast (mcurrentactivity, r.string.tips_download_photo_faile);} Bitmap Bitmap = Bitmapfactory.decodefile (filepath);/Boolean flag = Imageutils.insertimagetoallbum (bitmap, mcurrentactivity);//if (flag) {////toastuti Ls.showlongtoast (mcurrentactivity, r.string.tips_download_photo_success);//}else {//ToastUtils.showLongToast ( Mcurrentactivity, R.string.tips_download_photo_faile);/}}}

Referring to the next article, find the following method to solve the problem of the majority of models, and you can save the photos to the system camera to take pictures of the directory. For everyone's reference.

Private classDownloadtaskextendsAsynctask<string, Integer, boolean> {        Privatecontext Context;  Public intFilelength = 0; PrivateBitmap bmp;  PublicDownloadtask (Context context) { This. Context =context; File Cachedir=NewFile (Imageloader.getexternalcachedir (context). GetAbsolutePath ()); if(!cachedir.exists ())            {Cachedir.mkdirs (); }} @SuppressWarnings ("Resource") @OverrideprotectedBoolean doinbackground (String ... surl) {powermanager pm=(PowerManager) Context.getsystemservice (Context.power_service); Powermanager.wakelock WL=Pm.newwakelock (Powermanager.partial_wake_lock, GetClass (). GetName ());            Wl.acquire (); InputStream input=NULL; Bytearrayoutputstream Output=NULL; HttpURLConnection Connection=NULL; Try{URL URL=NewURL (surl[0]); Connection=(HttpURLConnection) url.openconnection (); Connection.setconnecttimeout (5000); Connection.setreadtimeout (20000);                Connection.connect (); //expect HTTP $ OK, so we don ' t mistakenly save error report//instead of the file                if(Connection.getresponsecode ()! =HTTPURLCONNECTION.HTTP_OK)return false; Filelength=connection.getcontentlength (); Input=Connection.getinputstream (); Output=NewBytearrayoutputstream (); byteData[] =New byte[4096]; LongTotal = 0; intcount;  while((count = input.read (data))! =-1) {                    //Allow canceling with the back button                    if(iscancelled ())return false; Total+=count; if(Filelength > 0)//Only If total length is knownPublishprogress ((int) total); Output.write (data,0, Count); } BMP= Bitmapfactory.decodebytearray (Output.tobytearray (), 0, Output.tobytearray (). length); return true; } Catch(Exception e) {return false; } finally {                Try {                    if(Output! =NULL) Output.close (); if(Input! =NULL) Input.close (); } Catch(IOException ignored) {}if(Connection! =NULL) Connection.disconnect ();            Wl.release (); }} @Overrideprotected voidonprogressupdate (Integer ... values) {//TODO auto-generated Method Stub            Super. Onprogressupdate (values); floatProgress = (float) values[0]/(float) Filelength; Mprogressinfo.settext (GetString (r.string.download_progress_info,stringutils.getkbunitstring (values[0]), stringutils.getkbunitstring (filelength)); Mprogressbar.setprogress ((int) (Progress * 100)); } @Overrideprotected voidOnPostExecute (Boolean result) {//TODO auto-generated Method Stub            Super. OnPostExecute (Result);            Mdownloadview.setvisibility (View.gone); if(Result.booleanvalue () &&imageutils.insertimagetoallbum (BMP, Mcurrentactivity)) {                            }Else{toastutils.showlongtoast (mcurrentactivity, r.string.tips_download_photo_faile); }                    }    }

The difference between the two methods is that the FileOutputStream is replaced by the Bytearrayoutputstream project, which has the requirement of displaying the download progress bar, so it is slightly more complicated.

In addition: The Insertimage method in Imageutils is as follows.

public static Boolean insertimagetoallbum (Bitmap bitmap,context mcontext) {if (Bitmap! = null) {String URI = mediastore.im Ages. Media.insertimage (Mcontext.getcontentresolver (), Bitmap, "", "" "); Textutils.isempty (URI)) {String FilePath = Getrealpathfromuri (Uri.parse (URI), mcontext); Toastutils.showlongtoast (Mcontext, mcontext.getstring (R.string.tips_img_save_path, FilePath)); ScanFile (MContext, FilePath); return true;}} return false;} public static void Scanfile (Context mcontext,string path) {mediascannerconnection.scanfile (Mcontext, new string[] {path }, Null,new Mediascannerconnection.onscancompletedlistener () {public void onscancompleted (String path, Uri uri) {}});

Method Scanfile is to have the system reload the SD card.

Over, have questions please leave a message, welcome to correct mistakes.

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.