如何使用Android ImageView应用程序在drawable文件夹中打开图像?

3

我希望通过手机上默认的图片查看应用程序(相册等)打开我的drawable文件夹中的图像。

我的图片位置:drawable/image.png

代码:

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(""), "image/*");
startActivity(intent);

我需要在Uri.parse函数中写什么才能查看图像文件?

3个回答

4

要实现这个功能,您需要将图像从drawable文件夹复制到SD卡中,然后将SD卡中文件的路径提供给意图。

以下是代码:

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.imagename);

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

        File f = new File(Environment.getExternalStorageDirectory()
                + File.separator + "test.jpg");
        try {
            f.createNewFile();
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            fo.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


        Uri path = Uri.fromFile(f);
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(path, "image/*");
        startActivity(intent);

请注意,imagename是您的drawable文件夹中图像的名称。

不要忘记在manifest文件中添加访问SD卡的permission

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

谢谢您的回答,但我想支持那些没有SD卡的手机。是否可以使用本地存储来解决这个问题? - suphero
是的,可以将图像存储在手机的内部存储器中。您可以参考此链接:http://developer.android.com/training/basics/data-storage/files.html - Abhishek V

1

我认为你做不到。这个drawable是私有的,只能被你的应用程序使用,其他应用程序无法使用它。你应该创建自己的ImageViewer或将这些可绘制对象复制到SD卡中,并在启动Intent时设置相应的Uri


我可以将文件夹从drawable切换到assets,这个文件夹也可以这样吗? - suphero

0

你可以通过以下代码访问你的图片:

R.drawable.image

例如,您可以在“onCreate”方法中使用此代码:
ImageView img = new ImageView(this);
img.setImageDrawable(R.drawable.image);

我不想用我的图片查看器打开图像文件。我想用相册/QuickPic/Instagram等应用程序打开它。 - suphero

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