网络获取图片

package com.itheima.image;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

public class MainActivity extends Activity {
	private EditText pathET;
	private NetService service;
	private ImageView picIV;
	private Handler handler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		picIV = (ImageView) findViewById(R.id.picIV);
		pathET = (EditText) findViewById(R.id.pathET);
		service = new NetService(getCacheDir());
	}

	public void go(View v) {
		final ProgressDialog dialog = new ProgressDialog(this);
		dialog.setCancelable(false);	// 设置进度条不能被取消
		dialog.show();					// 显示进度条
		
		new Thread() {
			public void run() {
				try {
					String path = pathET.getText().toString().trim();	// 获取路径
					final Bitmap bm = service.getImage(path);			// 访问网络, 获取图片
					handler.post(new Runnable() {						// 给主线程发送一个Runnable
						public void run() {
							picIV.setImageBitmap(bm);					// 主线程设置图片
							dialog.dismiss();
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

}



package com.itheima.image;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class NetService {
	private File cacheDir;

	public NetService(File cacheDir) {
		this.cacheDir = cacheDir;
	}

	public Bitmap getImage(String path) throws Exception {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);	// 设置超时时间, 连接网络的时候, 如果超过5000毫秒没有响应, 就抛出异常
		
		File file = new File(cacheDir, URLEncoder.encode(path, "UTF-8"));
		if (file.exists()) {			// 判断缓存文件是否存在
			conn.setIfModifiedSince(file.lastModified());		// 如果存在, 就设置请求头: 最后修改时间
		}
		
		int code = conn.getResponseCode();
		System.out.println(code);
		if (code == 200) {
			InputStream in = conn.getInputStream();				// 获取输入流
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buffer = new byte[8192];
			int length;
			while((length = in.read(buffer)) != -1) 			// 从网络读取数据
				out.write(buffer, 0, length);					// 把数据写到内存
			in.close();
			out.close();
			
			byte[] data = out.toByteArray();					// 获取内存中的所有数据
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(data);		// 把图片数据写到本地, 作为缓存(推荐在新线程中操作, 用户感受会更好)
			fos.close();
			
			Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);	// 把字节数据解码为Bitmap 
			return bm;
		} else if (code == 304) {
			return BitmapFactory.decodeFile(file.getAbsolutePath());	// 读取本地文件, 创建一个Bitmap
		}
		
		throw new RuntimeException("网络出错: " + code);
	}

}

<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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" >

    <Button
        android:id="@+id/goBT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:onClick="go"
        android:text="Go" />

    <EditText
        android:id="@+id/pathET"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@id/goBT"
        android:layout_toLeftOf="@id/goBT"
        android:hint="请输入要访问的地址"
        android:inputType="textUri"
        android:text="http://192.168.1.228:8080/05.Web/a.jpg" />

    <ImageView
        android:id="@+id/picIV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/pathET"
        android:layout_marginTop="10dp" />

</RelativeLayout>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值