【android】简单的根据url下载图片的一个类
16lz
2022-03-16
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;
public class DownloadFileUtil {
public static Bitmap downloadFile( String url) {
Bitmap bitmap = null;
try {
/*// //////////////取得的是byte数组, 从byte数组生成bitmap
byte[] data = getImage(url);
if (data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);// bitmap
imageView.setImageBitmap(bitmap);// display image
} else {
// Toast.makeText(AndroidTest2_3_3.this, "Image error!",
// 1).show();
}*/
// ******** 取得的是InputStream,直接从InputStream生成bitmap ***********/
bitmap = BitmapFactory.decodeStream(getImageStream(url));
// ********************************************************************/
} catch (Exception e) {
//Toast.makeText(AndroidTest2_3_3.this, "Newwork error!", 1).show();
e.printStackTrace();
}
return bitmap;
}
private static byte[] getImage(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
InputStream inStream = conn.getInputStream();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return readStream(inStream);
}
return null;
}
private 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();
}
private static InputStream getImageStream(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return conn.getInputStream();
}
return null;
}
}
更多相关文章
- 解决Cocos2d-x3.1编译生成Android程序出现Android(安卓)NDK:Abor
- Android(安卓)APP增量升级的实现方式
- Android文件上传
- 移植unrar到Android
- 2.Retrofit上传list数组给后端
- android之获得当前连接wifi的名字
- AndroidStudio3.6导入项目出现unable to find valid certificati
- Android(安卓)MD5加密
- 在android中创建包含对象数组对象List 的Parcelable