Android—根据URL获取Bitmap图片

1、根据图片的URL路径来获取网络图片,核心代码如下:
(1)
public static Bitmap getBitmap(String path) throws IOException{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
InputStream inputStream = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
return null;
}


public static Bitmap getBitMBitmap(String urlpath) {
 Bitmap map = null;
 try {
  URL url = new URL(urlpath);
  URLConnection conn = url.openConnection();
  conn.connect();
  InputStream in;
  in = conn.getInputStream();
  map = BitmapFactory.decodeStream(in);
 // TODO Auto-generated catch block
  } catch (IOException e) {
  e.printStackTrace();
 }
 return map;
}

(2)看评论

</pre>(3)<pre name="code" class="java">/**
* 得到本地或者网络上的bitmap url - 网络或者本地图片的绝对路径,比如:
* 
* A.网络路径: url="http://blog.foreverlove.us/girl2.png" ;
* 
* B.本地路径:url="file://mnt/sdcard/photo/image.png";
* 
* C.支持的图片格式 ,png, jpg,bmp,gif等等
* 
* @param url
* @return
*/
public static Bitmap GetLocalOrNetBitmap(String url)
{
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try
{
in = new BufferedInputStream(new URL(url).openStream(), Constant.IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, Constant.IO_BUFFER_SIZE);
copy(in, out);
out.flush();
byte[] data = dataStream.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
data = null;
return bitmap;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}

    //Constant.IO_BUFFER_SIZE 是一个常量而已,可以改成常数,比如2*1024,其实取决于你的图片大小,自己根据图片的大小自己设定吧。。。。

参考:获取网络图片(Bitmap)至内存或者SD卡http://www.tuicool.com/articles/BJ3Efu

有待完善:————O(∩_∩)O~


你可能感兴趣的:(Android—根据URL获取Bitmap图片)