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~4 Tools.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(); }