图片下载
一.图片下载方式一
package com.outdoors.jinghuang.demo;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by jing.huang on 2016/12/8.
*/
public class DownLoadImageDemo extends Activity implements View.OnClickListener {
private Button startBt;
private ImageView showImage;
private String path = "https://img-my.youkuaiyun.com/uploads/201402/24/1393242467_3999.jpg";
private static final int DOWNLOAD_SUCCESS = 1003;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.down_load_image);
initView();
}
private void initView() {
startBt = (Button) findViewById(R.id.start_bt);
showImage = (ImageView) findViewById(R.id.show_image);
startBt.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.start_bt) {
//开始下载图片
new Thread(new Runnable() {
@Override
public void run() {
downLoadImage();
}
}).start();
}
}
private void downLoadImage() {
URL url = null;
HttpURLConnection connection;
InputStream inputStream = null;
try {
url = new URL(path);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
inputStream = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Message message = handler.obtainMessage();
message.what = DOWNLOAD_SUCCESS;
message.obj = bitmap;
handler.sendMessage(message);
//另一种方法:有时可能直接用BitmapFactory.decodeStream加载不出图片,可以用下面的方式试试
//开始是图片下载的地址不是这个,随便从网上找到一张图片,然后就拿来用了,
//http://www.158sucai.com/Picture/Flower/hua/147675.htm#down结果加载不出来,
// 就借用了其他网上资料的图片地址
// if (inputStream == null) {
// throw new RuntimeException("stream is null");
// } else {
// try {
// byte[] data = readStream(inputStream);
// if (data != null) {
// Bitmap bitmap;
// bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
// Message message = handler.obtainMessage();
// message.what = DOWNLOAD_SUCCESS;
// message.obj = bitmap;
// handler.sendMessage(message);
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// inputStream.close();
// }
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
inputStream = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DOWNLOAD_SUCCESS:
Bitmap bitmap = (Bitmap) msg.obj;
showImage.setImageBitmap(bitmap);
break;
default:
break;
}
}
};
/*
* 得到图片字节流 数组大小
* */
public static byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
inStream.close();
return outStream.toByteArray();
}
}
延伸API
public void setDoInput(boolean doinput)将此 URLConnection 的 doInput 字段的值设置为指定的值。
URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输入,则将 DoInput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 true。
public void setDoOutput(boolean dooutput)将此 URLConnection 的 doOutput 字段的值设置为指定的值。
URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输出,则将 DoOutput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 false。
二.图片下载方式二
package com.outdoors.jinghuang.demo;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by jing.huang on 2016/12/10.
*/
public class DownLoadImageDemo2 extends Activity implements View.OnClickListener {
private Button startBt;
private ProgressBar showProgress;
private ImageView showImage;
private TextView progressTv;
private String path = "https://img-my.youkuaiyun.com/uploads/201402/24/1393242467_3999.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.down_load_image);
initView();
}
private void initView() {
startBt = (Button) findViewById(R.id.start_bt);
showImage = (ImageView) findViewById(R.id.show_image);
showProgress = (ProgressBar) findViewById(R.id.progress);
progressTv = (TextView) findViewById(R.id.progress_tv);
startBt.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.start_bt) {
//点击开始下载
showProgress.setVisibility(View.VISIBLE);
progressTv.setVisibility(View.VISIBLE);
MyAsyncImageDownLoad load = new MyAsyncImageDownLoad();
load.execute(path);//execute方法的参数是AsyncTask<String, Integer, Bitmap>中的String参数
}
}
private class MyAsyncImageDownLoad extends AsyncTask<String, Integer, Bitmap> {
private int currentDataSize;
private int currentLoadProgress;
private Bitmap bitmap;
@Override
protected void onPreExecute() {
super.onPreExecute();
//设置进度条的最大值
showProgress.setMax(100);
}
@Override
protected Bitmap doInBackground(String... strings) {//AsyncTask<String, Integer, Bitmap>的String参数
ByteArrayOutputStream baos = null;
InputStream inputStream = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int contentLength = connection.getContentLength();
// connection.setDoInput(true);//这一步不需要,否则会报异常java.lang.IllegalStateException: Already connected
// connection.connect();//这一步可以写也可以不写
inputStream = connection.getInputStream();
baos = new ByteArrayOutputStream();
int length = 0;
byte[] bt = new byte[8];
while (true) {
length = inputStream.read(bt, 0, bt.length);
if (length < 0) {
break;
}
currentDataSize += length;
currentLoadProgress = (int) (100 * currentDataSize / contentLength);
baos.write(bt, 0, length);
publishProgress(currentLoadProgress);
}
byte[] bytes = baos.toByteArray();
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (baos != null) {
try {
baos.close();
baos = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
inputStream = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bitmap;
}
@Override
protected void onProgressUpdate(Integer... values) {//AsyncTask<String, Integer, Bitmap>的Integer参数
super.onProgressUpdate(values);
showProgress.setProgress(values[0]);
progressTv.setText("已下载:"+showProgress.getProgress()+"%");
}
@Override
protected void onPostExecute(Bitmap bitmap) {//AsyncTask<String, Integer, Bitmap>的Bitmap参数
super.onPostExecute(bitmap);
showImage.setImageBitmap(bitmap);
showProgress.setVisibility(View.GONE);
progressTv.setVisibility(View.GONE);
}
}
}
一.图片下载方式一
package com.outdoors.jinghuang.demo;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by jing.huang on 2016/12/8.
*/
public class DownLoadImageDemo extends Activity implements View.OnClickListener {
private Button startBt;
private ImageView showImage;
private String path = "https://img-my.youkuaiyun.com/uploads/201402/24/1393242467_3999.jpg";
private static final int DOWNLOAD_SUCCESS = 1003;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.down_load_image);
initView();
}
private void initView() {
startBt = (Button) findViewById(R.id.start_bt);
showImage = (ImageView) findViewById(R.id.show_image);
startBt.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.start_bt) {
//开始下载图片
new Thread(new Runnable() {
@Override
public void run() {
downLoadImage();
}
}).start();
}
}
private void downLoadImage() {
URL url = null;
HttpURLConnection connection;
InputStream inputStream = null;
try {
url = new URL(path);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
inputStream = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Message message = handler.obtainMessage();
message.what = DOWNLOAD_SUCCESS;
message.obj = bitmap;
handler.sendMessage(message);
//另一种方法:有时可能直接用BitmapFactory.decodeStream加载不出图片,可以用下面的方式试试
//开始是图片下载的地址不是这个,随便从网上找到一张图片,然后就拿来用了,
//http://www.158sucai.com/Picture/Flower/hua/147675.htm#down结果加载不出来,
// 就借用了其他网上资料的图片地址
// if (inputStream == null) {
// throw new RuntimeException("stream is null");
// } else {
// try {
// byte[] data = readStream(inputStream);
// if (data != null) {
// Bitmap bitmap;
// bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
// Message message = handler.obtainMessage();
// message.what = DOWNLOAD_SUCCESS;
// message.obj = bitmap;
// handler.sendMessage(message);
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// inputStream.close();
// }
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
inputStream = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DOWNLOAD_SUCCESS:
Bitmap bitmap = (Bitmap) msg.obj;
showImage.setImageBitmap(bitmap);
break;
default:
break;
}
}
};
/*
* 得到图片字节流 数组大小
* */
public static byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
inStream.close();
return outStream.toByteArray();
}
}
延伸API
public void setDoInput(boolean doinput)将此 URLConnection 的 doInput 字段的值设置为指定的值。
URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输入,则将 DoInput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 true。
public void setDoOutput(boolean dooutput)将此 URLConnection 的 doOutput 字段的值设置为指定的值。
URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输出,则将 DoOutput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 false。
二.图片下载方式二
package com.outdoors.jinghuang.demo;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by jing.huang on 2016/12/10.
*/
public class DownLoadImageDemo2 extends Activity implements View.OnClickListener {
private Button startBt;
private ProgressBar showProgress;
private ImageView showImage;
private TextView progressTv;
private String path = "https://img-my.youkuaiyun.com/uploads/201402/24/1393242467_3999.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.down_load_image);
initView();
}
private void initView() {
startBt = (Button) findViewById(R.id.start_bt);
showImage = (ImageView) findViewById(R.id.show_image);
showProgress = (ProgressBar) findViewById(R.id.progress);
progressTv = (TextView) findViewById(R.id.progress_tv);
startBt.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.start_bt) {
//点击开始下载
showProgress.setVisibility(View.VISIBLE);
progressTv.setVisibility(View.VISIBLE);
MyAsyncImageDownLoad load = new MyAsyncImageDownLoad();
load.execute(path);//execute方法的参数是AsyncTask<String, Integer, Bitmap>中的String参数
}
}
private class MyAsyncImageDownLoad extends AsyncTask<String, Integer, Bitmap> {
private int currentDataSize;
private int currentLoadProgress;
private Bitmap bitmap;
@Override
protected void onPreExecute() {
super.onPreExecute();
//设置进度条的最大值
showProgress.setMax(100);
}
@Override
protected Bitmap doInBackground(String... strings) {//AsyncTask<String, Integer, Bitmap>的String参数
ByteArrayOutputStream baos = null;
InputStream inputStream = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int contentLength = connection.getContentLength();
// connection.setDoInput(true);//这一步不需要,否则会报异常java.lang.IllegalStateException: Already connected
// connection.connect();//这一步可以写也可以不写
inputStream = connection.getInputStream();
baos = new ByteArrayOutputStream();
int length = 0;
byte[] bt = new byte[8];
while (true) {
length = inputStream.read(bt, 0, bt.length);
if (length < 0) {
break;
}
currentDataSize += length;
currentLoadProgress = (int) (100 * currentDataSize / contentLength);
baos.write(bt, 0, length);
publishProgress(currentLoadProgress);
}
byte[] bytes = baos.toByteArray();
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (baos != null) {
try {
baos.close();
baos = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
inputStream = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bitmap;
}
@Override
protected void onProgressUpdate(Integer... values) {//AsyncTask<String, Integer, Bitmap>的Integer参数
super.onProgressUpdate(values);
showProgress.setProgress(values[0]);
progressTv.setText("已下载:"+showProgress.getProgress()+"%");
}
@Override
protected void onPostExecute(Bitmap bitmap) {//AsyncTask<String, Integer, Bitmap>的Bitmap参数
super.onPostExecute(bitmap);
showImage.setImageBitmap(bitmap);
showProgress.setVisibility(View.GONE);
progressTv.setVisibility(View.GONE);
}
}
}