Android实现图片下载并保存SD卡

时间:2024-01-09 13:05:44

一、首先获取图片

//第一种获取图片的方法

 String filePath = downloadUrl;
//以下是取得图片的方法
取得的是InputStream,直接从InputStream生成bitmap
mBitmap = BitmapFactory.decodeStream(getImageStream(filePath)); public 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;
}

//第二种获取图片的方法

 String filePath = downloadUrl;
//以下是取得图片的方法
取得的是byte数组, 从byte数组生成bitmap
byte[] data = getImage(filePath);
if(data!=null){
mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}else{
Toast.makeText(MainActivity.this, "Image error!", Toast.LENGTH_SHORT).show();
}
public 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;
}
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();
}

二、保存图片

 **
* 保存bitmap到SD卡
* @param bitmap
*/
public void saveBitmapToSDCard(Bitmap bitmap) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(picPath);//picPath为保存SD卡路径
if (fos != null) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}

源码下载地址:https://download.csdn.net/download/daxudada/10272805

喜欢我的就关注我