Android显示网络图片

本文介绍了一种在Android应用中从网络加载图片到ImageView的方法。通过使用HttpURLConnection获取图片资源,并将其转换为Bitmap进行显示。文章提供了完整的Java代码示例。

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

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:gravity="center">
	<ImageView
		android:id="@+id/img"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"/>
</LinearLayout>

 

MyWebDemo.java:

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class MyWebDemo extends Activity {
	private static final String PATH = "http://image2.sina.com.cn/pfp/ask/images/zhishi/logo_zhishi.gif"; 
	private ImageView img = null ;									// 定义图片显示
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.main);						// 调用布局管理器
		this.img = (ImageView) super.findViewById(R.id.img) ;		// 取得组件
		try {
			byte data [] = this.getUrlData() ;						// 接收数据
			Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);	// 生成图形 
			this.img.setImageBitmap(bm) ;							// 显示图片
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public byte[] getUrlData() throws Exception {					// 取得网络图片数据
		ByteArrayOutputStream bos = null ;							// 内存输出流
		try {
			URL url = new URL(PATH) ;								// 定义URL
			bos = new ByteArrayOutputStream() ;						// 定义内存输出流
			byte data [] = new byte[1024] ;							// 每次读取1024
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();	// 打开连接
			InputStream input = conn.getInputStream() ;				// 取得输入流
			int len = 0 ;											// 接收读取长度
			while((len = input.read(data)) != -1) {					// 没有读取到底部
				bos.write(data, 0, len) ;							// 向内存中保存
			}
			return bos.toByteArray() ;								// 变为字节数组返回
		} catch (Exception e) {
			throw e ;
		} finally { 
			if (bos != null) {
				bos.close();										// 关闭输出流
			}
		}
	}
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值