如何将URL图像加载到位图,将其转换为可绘制并使用imageview显示

时间:2018-07-09 15:22:05

标签: java android firebase android-fragments

我有uri的{​​{1}}图像,但是我不知道如何将其加载到位图中,因为我需要剪切图像的四个角。

我通过提供可绘制的图标在firebase上进行了尝试,它确实可以正常工作,但在resource id上无法正常工作

下面是我的代码:

uri

如何使用 uri imagefile = model.getImageUri(); if (imagefile !=null){ imageView.setVisibility(View.VISIBLE); Resources res = c.getResources(); //How i'm loading the image Bitmap src = BitmapFactory.decodeResource(res, Integer.parseInt(imagefile)); RoundedBitmapDrawable dr = RoundedBitmapDrawableFactory.create(res, src); dr.setCornerRadius(Math.max(src.getWidth(), src.getHeight()) / 30.0f); imageView.setImageDrawable(dr); } 加载图像?这也将帮助我解决其他相关问题。谢谢

2 个答案:

答案 0 :(得分:1)

我建议您使用AsyncTask将进程保持在后台,以免滞后于UI:

ImageLoadAsyncTask.java

public class ImageLoadAsyncTask extends AsyncTask<Void, Void, Bitmap> {

    private String url;
    private ImageView imageView;

    public ImageLoadAsyncTask(String url, ImageView imageView) {
        this.url = url;
        this.imageView = imageView;
    }

    @Override
    protected Bitmap doInBackground(Void... params) {
        try {
            URL urlConnection = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlConnection.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);
        imageView.setImageBitmap(result);
    }
}

然后,使用此代码从Firebase加载图像:

ImageLoadAsyncTask imageLoadAsyncTask = new ImageLoadAsyncTask(url, imageView);
 imageLoadAsyncTask.execute();

祝你好运!

答案 1 :(得分:0)

您可以在此检查如何将Uri转换为Url(观看CommonsWare的答案)

How to convert android.net.Uri to java.net.URL?

这就是如何从URL加载位图(观看rajath的答案)

Load image from url