将位图保存到文件并返回包含位图图像的文件

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);

请帮帮我...


1
这行代码 File file = new File(bmp + ".png") 的含义是什么? - Festus Tamakloe
1
定义“文件错误”(例如,发布堆栈跟踪) - njzk2
1
@FestusTamakloe 我猜他错误地假设 bmp.toString() 将返回 bmp 的 name - Rafael T
你必须给你的文件一个真实的名字,bmp +“.png”是行不通的。请同时发布您的错误堆栈。 - the-ginger-geek
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;

   }

2

您不能这样写

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

and this line is also wrong

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"); 就像你第二次几乎做到了一样。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接