为了账号安全,请及时绑定邮箱和手机立即绑定

Android从URL加载到Bitmap

Android从URL加载到Bitmap

沧海一幻觉 2019-09-02 09:53:55
我有一个关于从网站加载图像的问题。我使用的代码是: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);但它总是返回一个空指针异常,程序崩溃了。该URL有效,似乎适用于其他所有人。我正在使用2.3.1。
查看完整描述

3 回答

?
MMMHUHU

TA贡献1834条经验 获得超8个赞

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;

    }

}


查看完整回答
反对 回复 2019-09-02
?
POPMUISE

TA贡献1765条经验 获得超5个赞

如果您使用Picasso或Glide或Universal-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) {}

});

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?) {}

})

对于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)

    }

});


查看完整回答
反对 回复 2019-09-02
?
喵喔喔

TA贡献1735条经验 获得超5个赞

我喜欢这些:


从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;

    }

请记住:


Android包括两个HTTP客户端:HttpURLConnection和Apache 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);


        }

    }


查看完整回答
反对 回复 2019-09-02
  • 3 回答
  • 0 关注
  • 1372 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信