簡體   English   中英

如何將URL圖像加載到位圖,將其轉換為可繪制並使用imageview顯示

[英]How to load url image to bitmap, convert it to drawable and display it with imageview

我從firebase獲得了一個uri圖像,但是我不知道如何將其加載到位圖中,因為我需要剪切圖像的四個角邊緣。

我通過提供可繪制圖標來嘗試使用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);

    }

如何使用uri加載圖像? 這也將幫助我解決其他相關問題。 謝謝

我建議您使用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();

祝好運!

您可以在此檢查如何將Uri轉換為Url(觀看CommonsWare的答案)

如何將android.net.Uri轉換為java.net.URL?

這就是如何從URL加載位圖(觀看rajath的答案)

從網址加載圖片

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM