在Android中進行圖像處理的任務時,有時我們希望將處理后的結(jié)果以圖像文件的格式保存在內(nèi)部存儲空間中,本文以此為目的,介紹將Bitmap對象的數(shù)據(jù)以PNG格式保存下來的方法。
1、添加權(quán)限
由于是對SD card進行操作,必不可少的就是為你的程序添加讀寫權(quán)限,需要添加的內(nèi)容如下:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
對這兩個權(quán)限進行簡要解釋如下:
"android.permission.MOUNT_UNMOUNT_FILESYSTEMS"-->允許掛載和反掛載文件系統(tǒng)可移動存儲"android.permission.WRITE_EXTERNAL_STORAGE"-->模擬器中sdcard中創(chuàng)建文件夾的權(quán)限
2、保存圖片的相關代碼
代碼比較簡單,在這里存儲位置是寫的絕對路徑,大家可以通過使用Environment獲取不同位置路徑。
Tips:在使用該函數(shù)的時候,記得把文件的擴展名帶上。
private void saveBitmap(Bitmap bitmap,String bitName) throws IOException { File file = new File("/sdcard/DCIM/Camera/"+bitName); if(file.exists()){ file.delete(); } FileOutputStream out; try{ out = new FileOutputStream(file); if(bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)) { out.flush(); out.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }PS:下面看下android中Bitmap對象怎么保存為文件
Bitmap類有一compress成員,可以把bitmap保存到一個stream中。
例如:
public void saveMyBitmap(String bitName) throws IOException { File f = new File("/sdcard/Note/" + bitName + ".png"); f.createNewFile(); FileOutputStream fOut = null; try { fOut = new FileOutputStream(f); } catch (FileNotFoundException e) { e.printStackTrace(); } mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut); try { fOut.flush(); } catch (IOException e) { e.printStackTrace(); } try { fOut.close(); } catch (IOException e) { e.printStackTrace(); } } 總結(jié)
以上所述是小編給大家介紹的Android中將Bitmap對象以PNG格式保存在內(nèi)部存儲中,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VEVB武林網(wǎng)網(wǎng)站的支持!
新聞熱點
疑難解答
圖片精選