Android从URL加载到位图

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

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

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

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

如果您使用Picasso或Universal-Image-Loader从url加载图像。
你可以简单地通过获取加载的位图

毕加索

 Picasso.with(this) .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) { } }); 

对于通用图像加载器

 imageLoader.loadImage(imageUrl, new SimpleImageLoadingListener() { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { // loaded bitmap is here (loadedImage) } }); 
 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; } } 

我喜欢这些:

从InputStream创build位图并返回它:

  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客户端HttpURLConnectionApache HTTP客户端。 对于姜饼和后来, HttpURLConnection是最好的select。

从Android 3.x Honeycomb或更高版本,您不能在UI线程上执行networkingIO ,并执行此操作会引发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); } } 

传递你的图片url:试试这个:

 private Bitmap getBitmap(String url) { File file=fileCache.getFile(url); Bitmap bm = decodeFile(file); if(bm!=null) return bm; try { Bitmap bitmap=null; URL ImageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection)ImageUrl.openConnection(); conn.setConnectTimeout(50000); conn.setReadTimeout(50000); conn.setInstanceFollowRedirects(true); InputStream is = conn.getInputStream(); OutputStream os = new FileOutputStream(file); Utils.CopyStream(is, os); os.close(); bitmap = decodeFile(file); return bitmap; } catch (Exception ex){ ex.printStackTrace(); return null; } } private Bitmap decodeFile(File file){ try { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(file),null,opt); final int REQUIRED_SIZE=70; int width_tmp=opt.outWidth, height_tmp=opt.outHeight; int scale=1; while(true){ if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE) break; width_tmp/=2; height_tmp/=2; scale*=2; } BitmapFactory.Options opte = new BitmapFactory.Options(); opte.inSampleSize=scale; return BitmapFactory.decodeStream(new FileInputStream(file), null, opte); } catch (FileNotFoundException e) {} return null; } 

创build类实用程序:

 public class Utils { public static void CopyStream(InputStream is, OutputStream os) { final int buffer_size=1024; try { byte[] bytes=new byte[buffer_size]; for(;;) { int count=is.read(bytes, 0, buffer_size); if(count==-1) break; os.write(bytes, 0, count); } } catch(Exception ex){} } } 

遵循方法在Android中获取位图的URL只是传递这个图像的链接,并得到位图。

 public static Bitmap getBitmapFromURL(String imgUrl) { try { URL url = new URL(imgUrl); 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; } } 

尝试这个:

 AQuery aq = new AQuery(getActivity()); aq.id(view.findViewById(R.id.image)).image(imageUrl, true, true, 0, 0, new BitmapAjaxCallback() { @Override public void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status){ iv.setImageBitmap(bm); } }.header("User-Agent", "android")); 

非常快的方法,这种方法工作非常快:

 private Bitmap getBitmap(String url) { File f=fileCache.getFile(url); //from SD cache Bitmap b = decodeFile(f); if(b!=null) return b; //from web try { Bitmap bitmap=null; URL imageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setInstanceFollowRedirects(true); InputStream is=conn.getInputStream(); OutputStream os = new FileOutputStream(f); Utils.CopyStream(is, os); os.close(); bitmap = decodeFile(f); return bitmap; } catch (Exception ex){ ex.printStackTrace(); return null; } } //decodes image and scales it to reduce memory consumption private Bitmap decodeFile(File f){ try { //decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f),null,o); //Find the correct scale value. It should be the power of 2. final int REQUIRED_SIZE=70; int width_tmp=o.outWidth, height_tmp=o.outHeight; int scale=1; while(true){ if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE) break; width_tmp/=2; height_tmp/=2; scale*=2; } //decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize=scale; return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); } catch (FileNotFoundException e) {} return null; } 
 Glide.with(context) .load("http://test.com/yourimage.jpg") .asBitmap() // переводим его в нужный формат .fitCenter() .into(new SimpleTarget<Bitmap>(100,100) { @Override public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) { // do something with you bitmap bitmap } });