Android从服务器获取图片的两种方法

本文介绍了如何通过网络获取图片并将其转换为Bitmap对象的方法,包括使用URL、HttpURLConnection和BitmapFactory等API来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值