Two common scenarios. 1, save a bitmap,2, directly download a picture and save.
1. Save a bitmap as a file
Public Static voidSavemybitmap (Bitmap mbitmap, String fileName) {//New FileFile f =NewFile (fileName); //new file output streamFileOutputStream FOut =NULL; Try{FOut=NewFileOutputStream (f); } Catch(FileNotFoundException e) {e.printstacktrace (); } //compress the bitmap to the file output streamMbitmap.compress (Bitmap.CompressFormat.JPEG, 100, FOut); Try{Fout.flush (); } Catch(IOException e) {e.printstacktrace (); } Try{fout.close (); } Catch(IOException e) {e.printstacktrace (); } }
Among them, the core method is the Compress method in the bitmap class.
Public Boolean int quality, OutputStream stream) { thrownew runtimeexception ("stub!" ); }
This method has three parameters, the first parameter is the compression format, the second is the compression quality (maximum is 100), and the third is the file output stream.
Public Static enum Compressformat { JPEG, PNG, WEBP; Private Compressformat () { } }
The above code is easy to know, the picture can choose three kinds of format compression.
2, directly download a picture and save
Public classDownloadtaskextendsAsynctask<string, Integer, string>{context context; PublicDownloadtask (Context context) { This. Context =context; } @Overrideprotectedstring Doinbackground (String ... strings) {//of the fileString FILEURL = strings[0]; //file nameString FileName = strings[1]; //file name extensionString Expandname = strings[2]; Try { //Download ImageURL U =NewURL (FILEURL); InputStream is=U.openstream (); DataInputStream Dis=NewDataInputStream (IS); //Save picture File byte[] buffer =New byte[1024]; intlength; FileOutputStream Fos=NewFileOutputStream (NewFile (FileName +expandname)); while(length = dis.read (buffer)) >0) {fos.write (buffer,0, length); } //scan the specified file for media updatesIntent Intent =NewIntent (Intent.action_media_scanner_scan_file); Uri URI= Uri.fromfile (NewFile (FileName +expandname)); Intent.setdata (URI); Context.sendbroadcast (Intent); } Catch(malformedurlexception Mue) {mue.printstacktrace (); } Catch(IOException IoE) {ioe.printstacktrace (); } Catch(SecurityException se) {se.printstacktrace (); } return(filename+expandname); } @Overrideprotected voidOnPostExecute (String fileName) {uiutil.toastmessage (context,"Download successful, Image saved to:" +fileName); }
Done
File storage for images in Android