【问题标题】:android, how to convert bitmap to file objectandroid,如何将位图转换为文件对象
【发布时间】:2017-06-07 13:40:52
【问题描述】:

我想将位图对象转换为文件对象。 但是,我想将文件对象存储在内存中,而不是存储在 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);



    }

【问题讨论】:

  • not in SDcard or internal storage, so that I can use the image file。不可能的。没有其他地方可以存放文件。
  • 好问题措辞太难了。

标签: android


【解决方案1】:

希望对你有帮助

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

【讨论】:

  • @谢谢!!!!!!!!!` ????你怎么能这么大声地批准这个解决方案?你说not in SDcard or internal storage,
  • 什么是bitmap.compress?为什么这个函数给出JPEG格式? 100 是多少?
  • @roghayehhosseini 它的质量
  • 我们如何为位图创建一个临时文件并将其发布到服务器
【解决方案2】:

对于那些正在寻找 Kotlin 代码来将位图转换为文件对象的人。这是我写的关于这个主题的详细文章。 Convert Bitmap to File in Android

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
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 2017-01-30
    相关资源
    最近更新 更多