Android 如何从 png 文件加载 ImageView?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2688169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:57:14  来源:igfitidea点击:

How to load an ImageView from a png file?

androidfileloadpngimageview

提问by Peter vdL

I take a picture with the camera using

我用相机拍照

Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
startActivityForResult( intent, 22 );

When the activity completes, I write the bitmap picture out to a PNG file.

活动完成后,我将位图图片写入 PNG 文件。

    java.io.FileOutputStream out = openFileOutput("myfile.png", Context.MODE_PRIVATE);
    bmp.compress(Bitmap.CompressFormat.PNG, 90, out);

That goes OK, and I can see the file is created in my app private data space.

没问题,我可以看到文件是在我的应用程序私有数据空间中创建的。

I'm having difficulty when I later want to display that image using an ImageView.

当我以后想使用 ImageView 显示该图像时遇到了困难。

Can anyone suggest code to do this?

任何人都可以建议代码来做到这一点吗?

If I try to create a File with path separators in, it fails. If I try to create a Uri from a name without separators, that fails.

如果我尝试创建一个带有路径分隔符的文件,它会失败。如果我尝试从没有分隔符的名称创建 Uri,则会失败。

I canopen the file OK using:

可以使用以下命令打开文件:

        java.io.FileInputStream in = openFileInput("myfile.png");

But that doesn't give me the Uri I need to set an image with

但这并没有给我设置图像所需的 Uri

   iv.setImageURI(u)

Summary: I have the picture in a png file in private app data. What's the code to set that into an ImageView?

摘要:我在私人应用程序数据中的 png 文件中有图片。将其设置为 ImageView 的代码是什么?

Thanks.

谢谢。

回答by CommonsWare

Try BitmapFactory.decodeFile()and then setImageBitmap()on the ImageView.

试试BitmapFactory.decodeFile()然后setImageBitmap()就可以了ImageView

回答by Apc

Also possible:

也可以:

java.io.FileInputStream in = openFileInput("myfile.png");
iv.setImageBitmap(BitmapFactory.decodeStream(in));

回答by user2107276

iv.setImageURI(Uri.fromFile(in));

回答by Bernd

Why not this way:

为什么不这样:

ImageView MyImageView = (ImageView)findViewById(R.id.imageView1);
Drawable d = Drawable.createFromPath( PATH TO FILE );
MyImageView.setImageDrawable(d);

回答by Nauman Khalid

bitmap = BitmapFactory.decodeFile(imageInSD);

回答by Alvaro

There should be no difference between decodeStream()and decodeFile(). decodeFile()method opens an inputstream and calls decodeStream(). This was already answered at this link

decodeStream()和之间应该没有区别decodeFile()decodeFile()方法打开一个输入流并调用decodeStream(). 这已经在此链接中得到了回答