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

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

源码下载地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android平台上,我们可以通过代码来实现将网络图片保存到本地相册的功能。具体实现过程如下: 1. 获取需要下载的图片链接。 2. 创建一个异步任务,利用HTTPURLConnection或者OKHttp框架下载图片。 3. 下载完成后,将图片转换成Bitmap对象。 4. 申请写入文件的权限,并判断SD卡是否可用。 5. 使用File对象创建一个图片文件。 6. 利用FileOutputStream将Bitmap对象写入图片文件中。 7. 刷新相册,确保新添加的图片能够被相册所识别。 至此,保存网络图片到相册的功能已经完成。 以下是实现代码: ```java private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { protected Bitmap doInBackground(String... urls) { String url = urls[0]; Bitmap bitmap = null; try { URL imageURL = new URL(url); HttpURLConnection conn = (HttpURLConnection) imageURL.openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); is.close(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } protected void onPostExecute(Bitmap result) { if (result != null) { // 申请写入文件的权限 if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); return; } // 判断sd卡是否可用 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // 创建图片文件 File imageFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "image_test.jpg"); try { // 将Bitmap对象写入图片文件中 FileOutputStream outputStream = new FileOutputStream(imageFile); result.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); // 100表示压缩率,即不压缩 outputStream.flush(); outputStream.close(); // 刷新相册以便查看新添加的图片 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri uri = Uri.fromFile(imageFile); intent.setData(uri); MainActivity.this.sendBroadcast(intent); Toast.makeText(MainActivity.this, "图片已保存到相册", Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } } else { Toast.makeText(MainActivity.this, "sd卡不可用", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(MainActivity.this, "下载失败", Toast.LENGTH_SHORT).show(); } } } ``` 在使用时,只需创建一个DownloadImageTask对象,调用execute方法即可: ```java DownloadImageTask downloadImageTask = new DownloadImageTask(); downloadImageTask.execute("http://www.example.com/image.jpg"); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值