Android,如何将位图转换为文件对象

3
我希望将位图对象转换为文件对象。但是,我希望将文件对象存储在内存中,而不是SD卡或内部存储器中,以便我可以使用图像文件而不保存在图库中。
以下代码仅用于获取位图并将其转换为较小的图像。
 public void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);

    if(resultCode != RESULT_OK)
        return;

    if(requestCode == PICK_FROM_CAMERA){

        imageUri = data.getData();



        Cursor c = this.getContentResolver().query(imageUri, null, null, null, null);
        c.moveToNext();
        absolutePath = c.getString(c.getColumnIndex(MediaStore.MediaColumns.DATA));

        Glide.with(this).load(imageUri).into(image);


        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 4;
        bitmap = BitmapFactory.decodeFile(absolutePath, options);



    }

不在SD卡或内部存储中,因此我无法使用图像文件。这是不可能的。没有其他地方可以存放文件。 - greenapps
问题表述得太困难了。 - greenapps
2个回答

21

希望这可以帮助你

private static void persistImage(Bitmap bitmap, String name) {
File filesDir = getAppContext().getFilesDir();
File imageFile = new File(filesDir, name + ".jpg");

OutputStream os;
try {
  os = new FileOutputStream(imageFile);
  bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
  os.flush();
  os.close();
} catch (Exception e) {
  Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
  }
}

1
@ 谢谢!!!!!!!你怎么能这么大声地批准这个解决方案呢?你说“不在SD卡或内部存储器中”。 - greenapps
什么是bitmap.compress?为什么这个函数会给出JPEG格式?100是什么意思? - roghayeh hosseini
@roghayehhosseini 这就是质量。 - Eldhopj
1
如何为位图创建临时文件并将其发布到服务器。 - pb007

3

对于那些正在寻找将位图转换为文件对象的 Kotlin 代码的人,这里是我在该主题上撰写的详细文章。在 Android 中将 Bitmap 转换为 File

fun bitmapToFile(bitmap: Bitmap, fileNameToSave: String): File? { // File name like "image.png"
        //create a file to write bitmap data
        var file: File? = null
        return try {
            file = File(Environment.getExternalStorageDirectory().toString() + File.separator + fileNameToSave)
            file.createNewFile()

            //Convert bitmap to byte array
            val bos = ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos) // YOU can also save it in JPEG
            val bitmapdata = bos.toByteArray()

            //write the bytes in file
            val fos = FileOutputStream(file)
            fos.write(bitmapdata)
            fos.flush()
            fos.close()
            file
        } catch (e: Exception) {
            e.printStackTrace()
            file // it will return null
        }
    }

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