2013-03-15 108 views
14

我有一個將位圖保存到文件的問題。 我的方法是這樣的:將位圖保存到文件並返回包含位圖圖像的文件

private File savebitmap(Bitmap bmp) { 
    String extStorageDirectory = Environment.getExternalStorageDirectory() 
      .toString(); 
    OutputStream outStream = null; 

    File file = new File(bmp + ".png"); 
    if (file.exists()) { 
     file.delete(); 
     file = new File(extStorageDirectory, bmp + ".png"); 
     Log.e("file exist", "" + file + ",Bitmap= " + bmp); 
    } 
    try { 
     outStream = new FileOutputStream(file); 
     bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream); 
     outStream.flush(); 
     outStream.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    Log.e("file", "" + file); 
    return file; 

} 

它給了我錯誤file.I的正在調用該方法是這樣的:

Drawable d = iv.getDrawable(); 
Bitmap bitmap = ((BitmapDrawable) d).getBitmap(); 
File file = savebitmap(bitmap); 

請幫我...

+1

這是排什麼文件文件=新的文件(BMP +」的含義。 PNG「);? – 2013-03-15 09:44:35

+1

定義「文件錯誤」(即帖子堆棧跟蹤) – njzk2 2013-03-15 09:45:28

+1

@FestusTamakloe我猜他錯誤地認爲'bmp.toString()'將返回bmp的名稱, – 2013-03-15 09:48:22

回答

32

我儘量讓你的代碼 一些更正我假設你想使用的文件名,而不是位圖作爲參數

private File savebitmap(String filename) { 
     String extStorageDirectory = Environment.getExternalStorageDirectory().toString(); 
     OutputStream outStream = null; 

     File file = new File(filename + ".png"); 
     if (file.exists()) { 
     file.delete(); 
     file = new File(extStorageDirectory, filename + ".png"); 
     Log.e("file exist", "" + file + ",Bitmap= " + filename); 
     } 
     try { 
     // make a new bitmap from your file 
     Bitmap bitmap = BitmapFactory.decodeFile(file.getName()); 

     outStream = new FileOutputStream(file); 
     bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream); 
     outStream.flush(); 
     outStream.close(); 
     } catch (Exception e) { 
     e.printStackTrace(); 
     } 
     Log.e("file", "" + file); 
     return file; 

    } 
+0

謝謝..它的作品.. !!! – AndiM 2013-03-15 12:54:08

+0

@Meghs不客氣。如果這有幫助,然後投票。謝謝 – 2013-03-15 13:05:28

2

你不能這樣寫

File file = new File(bmp + ".png"); 

,這行也有錯

file = new File(extStorageDirectory, bmp + ".png"); 

您必須給字符串值而不是位圖。

File file = new File(filename + ".png"); 
0

更改 File file = new File(bmp +「.png」); 至 File file = new File(extStorageDirectory,「bmp.png」);像你幾乎第二次做的那樣。