安卓如何下载一个1MB的图片文件并设置到ImageView上

5

我正在尝试下载一个1MB的图片文件,并将其保存为位图以填充ImageView,但是出现了错误。

06-13 13:39:48.149: ERROR/AndroidRuntime(1782):
java.lang.OutOfMemoryError: bitmap size exceeds VM budget

如何下载一张大图片?


重复:https://dev59.com/GXI-5IYBdhLWcg3wQV4Z - razlebe
1个回答

3

我曾经遇到过同样的问题。在将下载的位图设置为您的 ImageView 之前,您必须根据您的 ImageView 的宽度和高度压缩您的位图。

您需要创建一个如下所示的缩放位图:

 bm1=Bitmap.createScaledBitmap(bm, 300, 300,true);
imgView.setImageBitmap(bm1);

或者像这样压缩您的位图:

            OutputStream fOut = null;
                        File file = new File(strDirectoy,imgname);
                            fOut = new FileOutputStream(file);

                        bm1.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
                            fOut.flush();
                            fOut.close();

                MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());

bm1=Bitmap.createScaledBitmap(bm, 300, 300,true); imgView.setImageBitmap(bm1); 有时候它能正常工作,有时候它不工作。你能告诉我为什么吗? - Jyosna
如果不行,请尝试我提供的下一个方法。这将压缩并存储您的图像。之后,尝试使用URI为ImageView设置图像。 - Andro Selva

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