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

一、首先获取图片 

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

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();
}

二、保存图片

/**
 * 保存bitmapSD * @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();
    }
}

代码结束,如果有需要代码的可以下载

源码下载地址

发布了15 篇原创文章 · 获赞 2 · 访问量 9910
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览