【问题标题】:Android - Can't display image from filepath / Can't save image to deviceAndroid - 无法从文件路径显示图像/无法将图像保存到设备
【发布时间】:2016-08-25 08:38:23
【问题描述】:

我正在制作一个简单的笔记本应用程序,其中的笔记可以附有图像。我可以很好地拍照,拍照后,它会正确显示在便笺内的图像视图中。保存笔记后,照片的路径将保存在数据库中。路径已正确保存。接下来,当用户打开便笺时,在数据库中正确找到了路径——但是,我无法将它加载到 imageview 中。相反,图像视图变成白色。当我手动查看应该保存图像的文件夹时,我发现图像根本没有保存到手机或 SD 卡中,我不知道如何保存它。我一直在寻找整个互联网和 StackOverflow,但没有找到解决方案。

public void onIcTakePhotoClick(View icon) {
    File imageFile = null;
    Intent takePictureIntent;

    try {
        imageFile = ImageHelper.createImageFile(this);
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (imageFile != null) {
        mImagePath = imageFile.getAbsolutePath();
        //mImagePath = ImageHelper.getImagePath(imageFile);
        takePictureIntent = ImageHelper.dispatchTakePictureIntent(this, imageFile);
        startActivityForResult(takePictureIntent, ImageHelper.REQUEST_IMAGE_CAPTURE);
    } else {
        // error message
    }
}

以上所有方法(创建文件、路径和意图)都运行良好:

public static File createImageFile(Context context) throws IOException {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    return image;
}

public static Intent dispatchTakePictureIntent(Context context, File photoFile) {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
        // Continue only if the File was successfully created
        Uri photoURI = FileProvider.getUriForFile(context,
                "com.bergdahl.notebook.fileprovider",
                photoFile);
        //takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
        return takePictureIntent;
    }
    return null;
}

文件路径最终看起来像这样:“/storage/emulated/0/Android/data/com.myname.notebook/files/Pictures/JPEG_20160824_213643_135920553.jpg”。接下来我得到结果:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case ImageHelper.REQUEST_IMAGE_CAPTURE: {
            if (resultCode == RESULT_OK) {
                ImageHelper.handleCameraPhoto(this, imageView, mImagePath);
            }
            break;
        }
    }
}

其中我使用了 Android 团队 (https://developer.android.com/training/camera/photobasics.html) 创建的方法:

public static void handleCameraPhoto(Activity context, ImageView imageView, String imagePath) {
    if (imagePath != null) {
        ImageHelper.setPic(imagePath, imageView);
        ImageHelper.galleryAddPic(context, imagePath);
    }
}

public static void setPic(String imagePath, ImageView imageView) {

    /* There isn't enough memory to open up more than a couple camera photos */
    /* So pre-scale the target bitmap into which the file is decoded */

    /* Get the size of the ImageView */
    int targetW = imageView.getWidth();
    int targetH = imageView.getHeight();

    /* Get the size of the image */
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(imagePath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    /* Figure out which way needs to be reduced less */
    int scaleFactor = 1;
    if ((targetW > 0) || (targetH > 0)) {
        scaleFactor = Math.min(photoW/targetW, photoH/targetH);
    }

    /* Set bitmap options to scale the image decode target */
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    /* Decode the JPEG file into a Bitmap */
    Bitmap bitmap = BitmapFactory.decodeFile(imagePath, bmOptions);

    /* Associate the Bitmap to the ImageView */
    imageView.setImageBitmap(bitmap);
    imageView.setVisibility(View.VISIBLE);
}

public static void galleryAddPic(Activity context, String imagePath) {
    Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
    File f = new File(imagePath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    context.sendBroadcast(mediaScanIntent);
}

最后是稍后打开笔记的代码:

if (mNote.getFilePath() != null) {
        mImagePath = mNote.getFilePath();
        //ImageHelper.handleCameraPhoto(this, imageView, mNote.getFilePath());

        //File file = new File(mImagePath);
        //imageView.setImageDrawable(Drawable.createFromPath(mImagePath));

        //Uri uri = Uri.parse("file:" + mNote.getFilePath());
        //imageView.setImageURI(uri);
    }

在清单中,我指定了写入外部存储的权限。所以,重申一下,我需要帮助弄清楚如何将我拍摄的图像保存到设备上,以便以后在用户下次打开笔记时将其加载到图像视图中。提前感谢您的帮助!

编辑:我尝试了 image.createNewFile() 方法,但遗憾的是结果是一样的。布尔测试为真。

public static File createImageFile(Context context) throws IOException {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);

    /*
    File image = File.createTempFile(
            imageFileName,
            ".jpg",
            storageDir
    );
    */

    File image = new File(storageDir, imageFileName + ".jpg");

    if (!image.exists()) {
        try {
            boolean test = image.createNewFile();
            Log.d("createImageFile", test + "");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return image;
}

再次编辑:图像现在可以正确显示在模拟器上,但在我的实际设备上不起作用。模拟器运行6.0,我的设备6.0.1。我的设备已授予权限并具有外部存储。我一直在尝试更改目录,但没有成功。

【问题讨论】:

  • 使用的安卓设备版本?
  • 创建一个常规文件而不是临时文件。
  • 我正在运行 Android 6.0.1 的设备上进行测试。我对文件创建非常陌生,所以我不确定如何制作常规文件。你能给我举个例子来说明我如何创建一个吗?
  • 只需将File.createTempFile 替换为File.createNewFile。
  • 我试过了,但是 createNewFile 的工作方式不同,因为它只能在已经创建的 File 对象实例上调用(即 File file = new File(params), file.createNewFile() ),我不确定在我的示例中如何使用它。抱歉,我对此很陌生。

标签: java android image uri


【解决方案1】:

尝试替换

mImagePath = imageFile.getAbsolutePath();

与

mImagePath = "file:" + imageFile.getAbsolutePath();

【讨论】:

  • 感谢您的回复!不幸的是,我已经尝试过了,它没有任何区别。
  • 没有问题 :) 您是否尝试过将 mImagePath 而不是 imageFile 传递给 ImageHelper.dispatchTakePictureIntent。传递你得到的文件路径而不是文件本身。
【解决方案2】:

使用 Android 6,即使您已在清单中声明,安装后您也不会拥有读/写权限。您必须在运行时首先要求它:

https://developer.android.com/training/permissions/requesting.html

出于测试目的,您可以在应用设置菜单中为您的应用授予权限,而无需执行查询。

【讨论】:

  • 感谢您的回复!这对以后非常有用,但我已经手动为我的设备授予了适当的权限,所以很遗憾这不是问题。
【解决方案3】:

添加权限运行时..

 if (Build.VERSION.SDK_INT >= 23)
    {
        if (checkPermission())
        {
            // Code for above or equal 23 API Oriented Device 
            // Create a common Method for both
   ///take camera caputure code

        } else {
            requestPermission();
        }
    }
  else
    {

       // Code for Below 23 API Oriented Device 
       // Create a common Method for both
    }

现在添加 checkPermission() 和 requestPermission()

 private boolean checkPermission() {
    int result = ContextCompat.checkSelfPermission(Your_Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (result == PackageManager.PERMISSION_GRANTED) {
        return true;
    } else {
        return false;
    }
}

private void requestPermission() {

    if (ActivityCompat.shouldShowRequestPermissionRationale(Your_Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        Toast.makeText(Your_Activity.this, "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
    } else {
        ActivityCompat.requestPermissions(Your_Activity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e("value", "Permission Granted, Now you can use local drive .");
            } else {
                Log.e("value", "Permission Denied, You cannot use local drive .");
            }
            break;
    }
}

【讨论】:

  • 非常感谢您的回复!这对以后非常有用,但我已经手动为我的设备授予了适当的权限,所以很遗憾这不是问题。
  • 你能提供ImageHelper吗?
  • 啊,我的 ImageHelper 类中的每个方法都在原始问题中 :) 唯一没有列出的是基本请求代码(public static final int REQUEST_IMAGE_CAPTURE = 0;),这不是非常感兴趣。
猜你喜欢
  • 2019-01-08
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-27
  • 2019-12-14
  • 1970-01-01
  • 2016-06-12
相关资源
最近更新 更多