2013-03-15 101 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”);像你几乎第二次做的那样。