Load image from url

前端 未结 16 2304
独厮守ぢ
独厮守ぢ 2020-11-22 05:12

I have an image URL. I want to display an image from this URL in an ImageView but I am unable to do that.

How can this be achieved?

16条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 05:34

    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.widget.ImageView;
    import android.widget.Toast;
    
    public class imageDownload {
    
        Bitmap bmImg;
        void downloadfile(String fileurl,ImageView img)
        {
            URL myfileurl =null;
            try
            {
                myfileurl= new URL(fileurl);
    
            }
            catch (MalformedURLException e)
            {
    
                e.printStackTrace();
            }
    
            try
            {
                HttpURLConnection conn= (HttpURLConnection)myfileurl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                int length = conn.getContentLength();
                int[] bitmapData =new int[length];
                byte[] bitmapData2 =new byte[length];
                InputStream is = conn.getInputStream();
                BitmapFactory.Options options = new BitmapFactory.Options();
    
                bmImg = BitmapFactory.decodeStream(is,null,options);
    
                img.setImageBitmap(bmImg);
    
                //dialog.dismiss();
                } 
            catch(IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
    //          Toast.makeText(PhotoRating.this, "Connection Problem. Try Again.", Toast.LENGTH_SHORT).show();
            }
    
    
        }
    
    
    }
    

    in your activity take imageview & set resource imageDownload(url,yourImageview);

提交回复
热议问题