17

我在将位图保存到文件时遇到问题。我的方法是这样的:

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;

}

它给了我文件错误。我这样调用这个方法:

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

请帮我...

4

3 回答 3

35

我尝试对您的代码进行一些更正我假设您想使用文件名而不是位图作为参数

 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;

   }
于 2013-03-15T09:56:52.620 回答
2

你不能这样写

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

这条线也是错误的

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

您必须提供字符串值而不是位图。

 File file = new File(filename + ".png"); 
于 2013-03-15T09:50:14.003 回答
0

更改文件 file = new File(bmp + ".png"); to File file = new File(extStorageDirectory,"bmp.png"); 就像你第二次做的一样。

于 2013-03-15T09:50:21.287 回答