【问题标题】:Save bitmap to Android storage without losing quality将位图保存到 Android 存储而不会丢失质量
【发布时间】:2015-01-24 04:13:38
【问题描述】:

现在我有一个 Intent 可以打开手机的相机应用,允许用户拍照,然后使用新图像返回我的应用。有了这个,它返回一个位图。为了获取图片的 Uri 以便我可以将 ImageView 设置为它,我相信我必须先将它保存到存储中。唯一的问题是当我的应用程序打开它时,图像质量很差。在我必须压缩的部分,我将质量保持在 100,所以我不确定我做错了什么。

这是我启动相机 Intent 的方式:

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
    startActivityForResult(takePictureIntent, TAKE_PICTURE_INTENT_CODE);
}

这是我的处理方式:

//get result of image choosing
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);

    switch(requestCode) {

        case TAKE_PICTURE_INTENT_CODE:
            if(resultCode == RESULT_OK){
                Bundle extras = data.getExtras();
                Bitmap imageBitmap = (Bitmap) extras.get("data");
                try {
                    switchToCropFrag(createImageFileFromCamera(imageBitmap));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else if (resultCode != RESULT_CANCELED){
                Toast.makeText(this, "Failed to get image, please try again.", Toast.LENGTH_LONG).show();
            } else {    //user cancelled image picking
        }
    }
}

private Uri createImageFileFromCamera(Bitmap imageBitmap) throws IOException {
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        File directory = cw.getDir("temp", Context.MODE_PRIVATE);
        // Create imageDir
        File path = new File(directory, "temp.png");

        FileOutputStream fos = null;
        try {

            fos = new FileOutputStream(path);

            // Use the compress method on the BitMap object to write image to the OutputStream
            imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Uri.fromFile(path);
    }

对于 switchToCropFrag,它只是使用 Picasso 设置图像。当我让用户从他们的手机中选择一张已经在他们的图库中的照片时,图像质量很好。

【问题讨论】:

    标签: android image android-intent bitmap camera


    【解决方案1】:

    这样,它返回一个位图

    它返回一个缩略图。引用the documentation:

    如果 EXTRA_OUTPUT 不存在,则在额外字段中将小尺寸图像作为 Bitmap 对象返回

    您似乎认为它返回的是常规大小的图像,但事实并非如此。

    为了获取图片的Uri以便设置ImageView到它,我相信我必须先将它保存到存储中。

    如果这是您活动中的ImageView,则不需要UriCall setImageBitmap().

    【讨论】:

      猜你喜欢
      • 2012-07-26
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      相关资源
      最近更新 更多