【Android】儲存Bitmap到SD卡

來源:互聯網
上載者:User

標籤:android   style   class   blog   c   code   

1.開啟讀寫SD卡的許可權  

需要在AndroidManifest.xml加入如下代碼:

<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


第一種方法:

public  void saveBitmap(String bitName, Bitmap mBitmap) {File f = new File("/sdcard/" + bitName + ".png");try {f.createNewFile();} catch (IOException e) {Tools.ToastShort("在儲存圖片時出錯:" + e.toString());}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();}}


第二種方法:

1、

public boolean writePngFile(File outFile) { // 將在螢幕上繪製的圖形儲存到SD卡boolean resault = false; // 儲存標識,false為儲存失敗try {FileOutputStream fos = new FileOutputStream(outFile); // 建立檔案輸出資料流(寫檔案)if (editBitmap[0].compress(Bitmap.CompressFormat.PNG, 100, fos)) { // 將圖片對象按PNG格式壓縮(品質100%),寫入檔案resault = true; // 儲存成功}fos.flush(); // 重新整理fos.close();// 關閉流} catch (Exception e) {e.printStackTrace();}return resault;}

2、

public void saveBitmap() {final int fileIndex = getSharedPreferences("bitmapIndex",Context.MODE_PRIVATE).getInt("index", 0); // 從共用偏好的記錄中取出檔案流水號,首次從0開始new AlertDialog.Builder(this).setTitle("提示資訊") // 建立並顯示提示對話方塊.setIcon(android.R.drawable.ic_menu_manage) // 設定表徵圖.setMessage("儲存到SD卡: 鈞瓷" + fileIndex + ".png?") // 設定提示資訊.setPositiveButton("確定", new OnClickListener() { // 按下“確定”按鈕的處理public void onClick(DialogInterface dialog,int which) {File outFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator+ "鈞瓷/鈞瓷"+ fileIndex+ ".png");// 在SD卡上建立檔案if (MyCanvas.editArea.writePngFile(outFile)) { // 將繪製路徑繪製到位元影像,並壓縮儲存getSharedPreferences("bitmapIndex",Context.MODE_PRIVATE).edit().putInt("index",(fileIndex + 1) % 5).commit();// 流水號迴圈遞增0~4Tools.ToastShort("儲存成功!");isSave = false;if (index == 2) {ScreenNum = 1;MyCanvas.menu.creat();}}}}).setNegativeButton("取消", new OnClickListener() {// 按下“取消”按鈕的處理public void onClick(DialogInterface dialog,int which) {isSave = false;if (index == 2) {ScreenNum = 1;MyCanvas.menu.creat();}}}).create().show();}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.