標籤:android 儲存圖片 位元組流 buffered
頭幾天遇到一個問題:在安卓開發應用中儲存圖片到SD卡,並且 使用者在圖庫中搜到,類似於緩衝的那種形式。最開始的第一想法是改一下尾碼名,例如把一個圖片儲存為image1.txt,這樣儲存當然沒問題,但在應用中讀取中就不行了,後來也沒研究為什麼不能正常讀取,畢竟這種辦法太土鱉了。。。
今天有空上網搜了一下,發現使用byte流儲存到SD卡就可以滿足我的需求。下面我把正常儲存圖片檔案的代碼和儲存圖片byte流的代碼都貼出來,方便大家共同學習參考。
假設我的圖片的名字為 image1。
正常儲存圖片檔案的代碼(例如image1.png):
public static void savePhotoToSDCard(Bitmap photoBitmap,String path,String photoName){if (checkSDCardAvailable()) {File dir = new File(path);if (!dir.exists()){dir.mkdirs();}File photoFile = new File(path , photoName + ".png");FileOutputStream fileOutputStream = null;try {fileOutputStream = new FileOutputStream(photoFile);if (photoBitmap != null) {if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) {fileOutputStream.flush();//fileOutputStream.close();}}} catch (FileNotFoundException e) {photoFile.delete();e.printStackTrace();} catch (IOException e) {photoFile.delete();e.printStackTrace();} finally{try {fileOutputStream.close();} catch (IOException e) {e.printStackTrace();}}} }
下面是儲存圖片byte流的代碼,這樣sd卡就會有一個名為image1的檔案。
public static byte[] bitmapToBytes(Bitmap bm) {byte[] bytes = null;if (bm != null) {ByteArrayOutputStream baos = new ByteArrayOutputStream();bm.compress(Bitmap.CompressFormat.PNG, 100, baos);bytes = baos.toByteArray();}return bytes;}public static void savePhotoToSDCardByte(Bitmap photoBitmap,String path,String photoName){if (checkSDCardAvailable()) {File dir = new File(path);if (!dir.exists()){dir.mkdirs();}if(photoBitmap !=null){byte[] byteArray = bitmapToBytes(photoBitmap);File photoFile = new File(path , photoName);FileOutputStream fileOutputStream = null;BufferedOutputStream bStream = null;try {fileOutputStream = new FileOutputStream(photoFile);bStream = new BufferedOutputStream(fileOutputStream);bStream.write(byteArray);} catch (FileNotFoundException e) {photoFile.delete();e.printStackTrace();} catch (IOException e) {photoFile.delete();e.printStackTrace();} finally{try {bStream.close();} catch (IOException e) {e.printStackTrace();}}}//(photoBitmap !=null)} }
安卓儲存圖片到SD卡,使用byte流