android url图片保存到相册
时间: 2023-10-16 15:07:21 浏览: 180
您可以使用以下代码将URL中的图片保存到相册:
```java
// 异步下载图片
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... urls) {
String imageUrl = urls[0];
Bitmap bitmap = null;
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
// 保存图片到相册
saveImageToGallery(result);
}
}
// 保存图片到相册
private void saveImageToGallery(Bitmap bitmap) {
String fileName = System.currentTimeMillis() + ".jpg";
File fileDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File imageFile = new File(fileDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
// 发送广播通知相册更新
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(imageFile);
intent.setData(uri);
sendBroadcast(intent);
Toast.makeText(this, "图片已保存到相册", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
// 调用异步下载图片的方法
new DownloadImageTask().execute(imageUrl);
```
请注意,您需要在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
阅读全文