Android从URL加载到Bitmap

Tye*_*ans 68 java android bitmap

我有一个关于从网站加载图像的问题.我使用的代码是:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();
int height = display.getHeight();
Bitmap bit=null;
try {
    bit = BitmapFactory.decodeStream((InputStream)new URL("http://www.mac-wallpapers.com/bulkupload/wallpapers/Apple%20Wallpapers/apple-black-logo-wallpaper.jpg").getContent());
} catch (Exception e) {}
Bitmap sc = Bitmap.createScaledBitmap(bit,width,height,true);
canvas.drawBitmap(sc,0,0,null);
Run Code Online (Sandbox Code Playgroud)

但它总是返回一个空指针异常,程序崩溃了.该URL有效,似乎适用于其他所有人.我正在使用2.3.1.

sil*_*uke 169

public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        // Log exception
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 代码很好.但是"主线上的网络"会有例外.尝试在"异步任务"中使用它. (14认同)
  • 注意阻塞主线程.这应该在AsyncTask派生类中使用. (11认同)
  • 最明显你有用户许可互联网? (7认同)
  • 如何从https加载一个? (5认同)

Pha*_*inh 21

如果您使用PicassoGlideUniversal-Image-Loader从网址加载图像.
您可以简单地获取加载的位图

毕加索 (当前版本2.71828)

Java代码

Picasso.get().load(imageUrl).into(new Target() {
    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        // loaded bitmap is here (bitmap)
    }

    @Override
    public void onBitmapFailed(Drawable errorDrawable) { }

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {}
});
Run Code Online (Sandbox Code Playgroud)

Kotlin代码

Picasso.get().load(url).into(object : com.squareup.picasso.Target { 
    override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
         // loaded bitmap is here (bitmap)
    }

    override fun onPrepareLoad(placeHolderDrawable: Drawable?) {}

    override fun onBitmapFailed(e: Exception?, errorDrawable: Drawable?) {}
})
Run Code Online (Sandbox Code Playgroud)

对于Glide
Check 如何使用滑动将图像下载到位图中?

对于Universal-Image-Loader
Java代码

imageLoader.loadImage(imageUrl, new SimpleImageLoadingListener() 
{
    @Override
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) 
    {
         // loaded bitmap is here (loadedImage)
    }
});
Run Code Online (Sandbox Code Playgroud)


Dhr*_*val 9

我喜欢这些:

从InputStream创建Bitmap并返回它:

    public static  Bitmap downloadImage(String url) {
        Bitmap bitmap = null;
        InputStream stream = null;
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;

        try {
            stream = getHttpConnection(url);
            bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
            stream.close();
        }
        catch (IOException e1) {
            e1.printStackTrace();
            System.out.println("downloadImage"+ e1.toString());
        }
        return bitmap;
    }

  // Makes HttpURLConnection and returns InputStream

 public static  InputStream getHttpConnection(String urlString)  throws IOException {

        InputStream stream = null;
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();

        try {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();

            if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                stream = httpConnection.getInputStream();
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("downloadImage" + ex.toString());
        }
        return stream;
    }
Run Code Online (Sandbox Code Playgroud)

请记住:

Android包括两个HTTP客户端:HttpURLConnectionApache HTTP Client. 对于姜饼和后来,HttpURLConnection是最好的选择.

从Android 3.x Honeycomb或更高版本,您无法在UI线程上执行网络IO并执行此操作会抛出android.os.NetworkOnMainThreadException.您必须使用Asynctask,如下所示

/**     AsyncTAsk for Image Bitmap  */
    private class AsyncGettingBitmapFromUrl extends AsyncTask<String, Void, Bitmap> {


        @Override
        protected Bitmap doInBackground(String... params) {

            System.out.println("doInBackground");

            Bitmap bitmap = null;

            bitmap = AppMethods.downloadImage(params[0]);

            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {

            System.out.println("bitmap" + bitmap);

        }
    }
Run Code Online (Sandbox Code Playgroud)


小智 6

public Drawable loadImageFromURL(String url, String name) {
    try {
        InputStream is = (InputStream) new URL(url).getContent();
        Drawable d = Drawable.createFromStream(is, name);
        return d;
    } catch (Exception e) {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)


Abd*_*rek 6

此方法将使用 kotlin 协程来实现这一点,因此它不会阻塞 UI 主线程并将返回调整大小的圆形位图图像(如个人资料图像)

 private var image: Bitmap? = null
 private fun getBitmapFromURL(src: String?) {
    CoroutineScope(Job() + Dispatchers.IO).launch {
        try {
            val url = URL(src)
            val bitMap = BitmapFactory.decodeStream(url.openConnection().getInputStream())
            image = Bitmap.createScaledBitmap(bitMap, 100, 100, true)
        } catch (e: IOException) {
            // Log exception
        }
    }
}
Run Code Online (Sandbox Code Playgroud)