andorid中网络图片下载、保存以及在相册中显示
16lz
2021-01-26
String picUrl=”http://img2.3lian.com/2014/f3/82/68.jpg”;//要保存的图片Url
Bitmap bitmap = getPicBitmap(picUrl);
savePicture(bitmap);// 保存图片到SD卡中的指定目录
1、根据图片的URL获取图片getPicBitmap(url);
/** * 从网络获取图片 * * @param url * @return */ public Bitmap getPicBitmap(String url) { Bitmap bitmap = null; try { URL pictureUrl = new URL(url); InputStream in = pictureUrl.openStream(); bitmap = BitmapFactory.decodeStream(in); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bitmap; }
2、把图片保存到本地(自己指定目录)
@SuppressLint("SdCardPath") public void savePicture(Bitmap bitmap) { String temps = Environment.getExternalStorageDirectory() + "/ceshi/";//文件目录名字 String pictureName = temps + "ceshi" + bitmap.getGenerationId() + ".jpg";//文件名 File tempFiles = new File(temps); // 判断某个文件是否存在 if (!tempFiles.exists()) { tempFiles.mkdir(); } File file = new File(pictureName); FileOutputStream out; try { out = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); out.flush(); out.close(); toShowPic(file); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
3、本地图片保存之后发广播,更新图片(若不发广播更新,只能在文件管理中查看)
/** * 发广播更新图库 * @param file */ private void toShowPic(File file) { Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri uri = Uri.fromFile(file); intent.setData(uri); ShowBigPicActivity.this.sendBroadcast(intent); }
注意:获取网络图片过程不要在主线程中执行,否则程序会出现错误。
更多相关文章
- Android(安卓)Studio利用BuildConfig获取版本名和版本号
- Android获取本机ip地址和Mac地址
- android 通过Intent打开相册并获取选择的图片
- Android-- ArrayAdapter用法举例
- Android学习笔记(21):ImageView及其子类
- 一起学android之如何获取网络类型并判断是否可用(20)
- Android中保存Activity的状态
- Android中的图像处理
- Android(安卓)实现多图分享到微信朋友圈