2016-11-30 21 views
0

使用Intent(其中該圖像採用位圖的形式)從手機的相機應用程序中檢索圖像相對比較簡單。在Android應用程序中存儲圖片

我不知道這是否真的是一個合適的問題,但通常的做法是保存整個位圖原樣?或者大多數人壓縮/調整大小?

回答

1

你傾向於使用Bitmap.compress保存它,它會爲你壓縮它。隨意使用PNG,這是一種無損格式,所以當您重新填充它時不會發生質量損失。

當然,如果您正在使用意圖從相機獲取它,通常它已保存到文件系統。在這種情況下,該文件已經被壓縮了。

+0

所以,像'bmp.compress(Bitmap.CompressFormat.PNG,100);'地方保存前? – KaliMa

+0

看起來它需要一個輸出流。通常我使用MediaStore.Images.Media.insertImage(contentResolver,bitmap,title,description);'將位圖傳遞到庫中。有沒有辦法做到這一點與輸出流? – KaliMa

+0

因此,當您使用該MedaStore調用時,它實際上會創建縮小版圖像(縮略圖),並只將其保存到磁盤。沒有必要進一步縮小它。在將圖像保存到磁盤時,只有位圖壓縮存在,Bitmap對象中的位圖內存表示始終未壓縮。 –

0

這是一個簡單的方法如下:

private Boolean saveImage(Bitmap bitmap){ 

    ByteArrayOutputStream bao = null; 
    File file = null, image = null; 
    Boolean save = false; 

    try{ 

     bao = new ByteArrayOutputStream(); 
     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bao); 

     image = new File(Environment.getExternalStorageDirectory() + "", "/yourSelectedFolder/"); 

     if (!image.exists()) { 
      if (!image.mkdirs()) { 
       Toast.makeText(context, "Error: Folder Not Created!\nPlease Try Again.", Toast.LENGTH_LONG).show(); 
      } else { 
       Toast.makeText(context, "Folder Successfully Created!", Toast.LENGTH_LONG).show(); 
      } 
     } 


     file = new File(Environment.getExternalStorageDirectory().toString() + "/yourSelectedFolder/","filename" + ".jpeg"); 
     save = file.createNewFile(); 

     FileOutputStream fos = new FileOutputStream(file); 
     fos.write(bao.toByteArray()); 
     fos.close(); 



     if (save){ 
      Toast.makeText(context, "Image Successfully Saved", Toast.LENGTH_LONG).show(); 
     } else { 
      Toast.makeText(context, "Image Not Saved", Toast.LENGTH_LONG).show(); 
     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
     Toast.makeText(context, "Error: "+e, Toast.LENGTH_LONG).show(); 
    } 
    return save; 
} 
相關問題