位图图像在ImageView中未显示。

5
我创建了一个应用程序,允许用户从图库中选择图片或从相机拍照并上传到Web服务器。这段代码运行良好。现在,在另一个屏幕上,我正在从Web服务器下载图像并将其存储在SD卡中。问题是,如果从图库中选择图像,则该图像将显示在图像视图中,但如果从相机拍摄图像,则即使文件存在于SD卡中,该图像也不会显示在图像视图中。
显示图像和从服务器下载的代码
 private static class DownloadImage extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(String... params) {
            String filePath = downloadFile("my web service");
            return filePath;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            if (result.equalsIgnoreCase("")) {
                ivProfilePic.setImageDrawable(context.getResources().getDrawable(R.drawable.user_default));
                progressBar.setVisibility(View.GONE);
            } else {
              profilePicPath = result;
                Bitmap bitmapProfilePic = BitmapFactory.decodeFile(profilePicPath);
                ivProfilePic.setImageBitmap(bitmapProfilePic);



                progressBar.setVisibility(View.GONE);


            }


        }


    }

    public static String downloadFile(String url, String dest_file_path) {
        try {
            File dest_file = new File(dest_file_path);
            URL u = new URL(url);
            URLConnection conn = u.openConnection();
            int contentLength = conn.getContentLength();
            DataInputStream stream = new DataInputStream(u.openStream());
            byte[] buffer = new byte[contentLength];
            stream.readFully(buffer);
            stream.close();
            DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
            fos.write(buffer);
            fos.flush();
            fos.close();

        } catch (FileNotFoundException e) {

            return "";
        } catch (IOException e) {

            return "";
        }
        return dest_file_path;
    }

我能看到从相机拍照并将其显示到图像视图的代码吗? - Shrey
2个回答

13

在将图像显示到 ImageView 之前,您应该对其进行缩放。

我曾经遇到过同样的问题,通过对位图进行缩放解决了我的问题。

以下是实现缩放的代码-

Bitmap b = BitmapFactory.decodeByteArray(bitmapProfilePic , 0, bitmapProfilePic .length)
ivProfilePic.setImageBitmap(Bitmap.createScaledBitmap(b, 120, 120, false));

希望这能解决你的问题。

祝一切顺利。


这是一个正确的答案。以前在ImageView中使用大图片会出现问题。 - Juanjo Vega
我无法获取bitmapProfilePic.length。 - Anuj
我无法获取长度。 - Anuj

4
在KITKAT(API 19)设备上出现了这个问题,但在LOLLIPOP_MR1(API 22)的设备上没有。我猜API 22或以上版本不需要使用createScaledBitmap,但在运行低于API 19的设备上需要像这样操作:
Bitmap myPictureBitmap = BitmapFactory.decodeFile(imagePath);
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
    myPictureBitmap = Bitmap.createScaledBitmap(myPictureBitmap, ivMyPicture.getWidth(),ivMyPicture.getHeight(),true);
}
ivMyPicture.setImageBitmap(myPictureBitmap);

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