安卓儲存圖片到SD卡,使用byte流

來源:互聯網
上載者:User

標籤: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流

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.