[教程]安卓获取网络图片的例子
2014-04-23 20:48:45 -0400
package com.luoye.web;
import java.io.*;
import android.graphics.*;
import java.net.*;
import android.util.*;
public class WebBitmap
{
public Bitmap getPicture(String imgPath)
{
Bitmap bit=null;
try
{
URL url = new URL(imgPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(3000);
int code = conn.getResponseCode();
if (code == 200)
{
byte[] data = readStream(conn.getInputStream());
bit = BitmapFactory.decodeByteArray(data, 0, data.length);// 转化为图片
}
//返回位图对象
return bit;
}
catch (Exception e)
{
return null;
}
}
//读取图片流
private byte[] readStream(InputStream in) throws Exception
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = in.read(buffer)) != -1)
{
outputStream.write(buffer, 0, len);
}
outputStream.close();
in.close();
return outputStream.toByteArray();
}
}
Back to home
Subscribe |
Register |
Login
| N