標籤:
兩種常見情況。1、儲存一個bitmap,2、直接下載一個圖片並儲存。
1、將一個bitmap存成檔案
public static void saveMyBitmap(Bitmap mBitmap, String fileName) { // 建立檔案 File f = new File(fileName); // 建立檔案輸出資料流 FileOutputStream fOut = null; try { fOut = new FileOutputStream(f); } catch (FileNotFoundException e) { e.printStackTrace(); } // 將bitmap壓縮至檔案輸出資料流 mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut); try { fOut.flush(); } catch (IOException e) { e.printStackTrace(); } try { fOut.close(); } catch (IOException e) { e.printStackTrace(); } }
其中,核心的方法就是Bitmap類中的compress方法。
public boolean compress(Bitmap.CompressFormat format, int quality, OutputStream stream) { throw new RuntimeException("Stub!"); }
這個方法有三個參數,第一個參數是壓縮格式,第二個是壓縮品質(最大是100),第三個是檔案輸出資料流。
public static enum CompressFormat { JPEG, PNG, WEBP; private CompressFormat() { } }
由上面代碼易知,圖片可以選擇三種格式壓縮。
2、直接下載一個圖片並儲存
public class DownloadTask extends AsyncTask<String, Integer , String> { Context context; public DownloadTask(Context context){ this.context = context; } @Override protected String doInBackground(String... strings) { // 檔案的 String fileUrl = strings[0]; // 檔案名稱 String fileName = strings[1]; // 檔案的副檔名 String expandName = strings[2]; try { // 下載圖片 URL u = new URL(fileUrl); InputStream is = u.openStream(); DataInputStream dis = new DataInputStream(is); // 儲存圖片檔案 byte[] buffer = new byte[1024]; int length; FileOutputStream fos = new FileOutputStream(new File(fileName + expandName)); while ((length = dis.read(buffer))>0) { fos.write(buffer, 0, length); } // 掃描指定檔案使媒體更新 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri uri = Uri.fromFile(new File(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); } @Override protected void onPostExecute(String fileName) { UIUtil.toastMessage(context, "下載成功,圖片已儲存至:" + fileName); }
Done
Android中圖片的檔案儲存