1.直接获取bitmap对象
// 传输网络图片
public Bitmap getPic(String uriPic) {
URL imageUrl = null;
Bitmap bitmap = null;
try {
imageUrl = new URL(uriPic);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
2.0 利用输入流并转化为相应的比特流,最后再包装秤bitmap
public class ImageServer {
public static final int TIMEOUT = 5000;
public static final String REQUESTMETHOD = "POST";
public static final int MAX_ARRAY_SIZE = 40480;
public static byte [] getImg(String path) throws Exception{
// 包装统一资源定位符
URL url = new URL(path);
// 建立远程连接
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setConnectTimeout(TIMEOUT);
con.setRequestMethod(REQUESTMETHOD);
if (con.getResponseCode() == 200) {
InputStream is = con.getInputStream();
return read(is);
}
return null;
}
// 将输入流转换为比特流
private static byte [] read (InputStream is) throws Exception{
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte [] buffer = new byte[MAX_ARRAY_SIZE];
while ((is.read(buffer)) != -1) {
os.write(buffer);
is.close();
}
return os.toByteArray();
}
}