Android获取网络图片应用示例

1、养成好习惯,配置字符串资源文件 strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">网络图片查看器</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
	<string name="imgpath">输入图片地址:</string>
	<string name="getBtn">获取图片</string>
	<string name="error">获取图片失败</string>
</resources>

2、布局文件,使用垂直布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/imgpath"
        />
	
    <EditText android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/imgpathInput"
        android:text="http://avatar.csdn.net/B/E/7/1_gaotong2055.jpg"
        android:inputType="text" />
    <Button 
         android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/getBtn"
        android:id="@+id/getBtn"
        />
    <ImageView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imgView"
        />
</LinearLayout>

3、编写代码

这里为了方便看代码,都写在一个类里面了。

可以把里面的静态方法单独拆分出来,写在一个工具类中,结构更好。

public class MainActivity extends Activity implements OnClickListener {
	private EditText pathText;
	private ImageView imageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		pathText = (EditText) this.findViewById(R.id.imgpathInput);
		imageView = (ImageView) this.findViewById(R.id.imgView);
		Button button = (Button) this.findViewById(R.id.getBtn);
		button.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		String path = pathText.getText().toString();
		byte[] data = null;
		try {
			data = getImgData(path);
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, R.string.error, 1).show();
		}
		Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
		imageView.setImageBitmap(bitmap);
	}

	public static byte[] getImgData(String path) throws Exception {

		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);// 超时时间5秒
		conn.setRequestMethod("GET");
		if (conn.getResponseCode() == 200) {
			InputStream in = conn.getInputStream();
			return read(in);
		} else {
			Log.d("tong.getImg", "服务器无响应");
		}

		return null;
	}

	/**
	 * 从一个输入流中读取数据,并返回
	 * 
	 * @param in
	 * @return byte[] 数据
	 * @throws IOException
	 */
	public static byte[] read(InputStream in) throws IOException {
		// 开辟一个内存的区域,以写入数据
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[10240];
		int len = 0;
		while ((len = in.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		outStream.close();

		return outStream.toByteArray(); // 返回内存中的数据
	}

}


运行效果:







你可能感兴趣的:(Android获取网络图片应用示例)