【问题标题】:How to access saved bitmap as a file on android?如何在android上将保存的位图作为文件访问?
【发布时间】:2019-08-19 16:29:14
【问题描述】:

我正在将Bitmap(位图)保存到文件中,如下:

String fileName = "image.jpg"; 
try { 
  ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
  bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
  FileOutputStream fo = openFileOutput(fileName,
       Context.MODE_PRIVATE); 
  fo.write(bytes.toByteArray()); 
  fo.close(); 
} catch (Exception e) { 
e.printStackTrace(); 
}

如何将保存的图像作为文件访问?谢谢。

【问题讨论】:

  • 你的意思是你特别需要一个File 对象吗?因为您可以使用openFileInput() 获得InputStream。如果您确实需要File,到底是什么目的?也就是说,它只是供您的应用程序内部使用吗?还是需要外传?
  • 是的,我需要一个 File 对象。供我的应用内部使用。
  • 好吧,如果你绝对必须有一个File 对象,openFileOutput() 保存到的目录可以用getFilesDir() 获得,所以你的File 将是new File(getFilesDir(), fileName)

标签: android android-file


【解决方案1】:

试试这个。

String fileName = "image.jpg"; 
try { 
  String path = Environment.getExternalStorageDirectory().toString(); //path where the file will be stored.

  ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
  bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
  File file = new File(path,fileName); // the File to save , append 
  FileOutputStream fo = new FileOutputStream(file);
  fo.write(bytes.toByteArray()); 
  fo.close(); 
} catch (Exception e) { 
e.printStackTrace(); 
}

不要忘记添加存储权限并在运行时获得权限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多