一、保存图片(集)到本地
1.保存单张图片到本地,这里使用的是ImageLoader加载的图片,通过ImageLoader.getInstance().loadImageSync(path)返回图片的位图。
// 保存图片 private Runnable saveFileRunnable = new Runnable() { @Override public void run() { try { //注释掉的代码是之前用的比较繁琐的方法来保存图片到本地 // Drawable drawable = SaveImageUtil.loadImageFromNetwork( // listMImage.get(indexImage).getImgPath()); // if (drawable == null) { // mSaveMessage = getString( // R.string.language_pictureSavedFailed); // } else { // BitmapDrawable bd = (BitmapDrawable) drawable; // mBitmap = bd.getBitmap(); // } //loadImage是异步加载;方法loadImageSync是同步加载,待图片资源加载完毕,直接返回位图(bitmap)资源对象 mBitmap = ImageLoader.getInstance().loadImageSync(listMImage.get(indexImage).getImgPath()); SaveImageUtil.saveFile(mBitmap, listMImage.get(indexImage).getImgPath(), getActivity()); mSaveMessage = getString(R.string.language_pictureSavedSuccessfully); } catch (Exception e) { mSaveMessage = getString(R.string.language_pictureSavedFailed); e.printStackTrace(); } messageHandler.sendMessage(messageHandler.obtainMessage()); } };
private Handler messageHandler = new Handler() { @Override public void handleMessage(Message msg) { showToast(mSaveMessage); } };
2.保存图片集到本地,也就是添加了一个循环,循环保存集合中的图片
//保存所有的图片 private Runnable saveAllFileRunnable = new Runnable() { @Override public void run() { try { downloadNum = 0; for (int i = 0; i < listMImage.size(); i++) { if (listMImage.get(i).getMark() == 1) {//只保存已经上传了的所有图片 downloadNum++; mBitmap = ImageLoader.getInstance().loadImageSync(listMImage.get(i).getImgPath()); SaveImageUtil.saveFile(mBitmap, listMImage.get(i).getImgPath(), getActivity()); } } if (downloadNum >= getServerImage.size()) { mSaveMessage = getString(R.string.language_pictureSavedSuccessfully); dismissProgressDialog();//隐藏提示正在保存图片的Dialog } } catch (Exception e) { dismissProgressDialog(); e.printStackTrace(); } if (isShareImage == false) messageHandler.sendMessage(messageHandler.obtainMessage()); } };
private Handler messageHandler = new Handler() { @Override public void handleMessage(Message msg) { showToast(mSaveMessage); } };
3.保存图片SaveImageUtil.saveFile()方法:
//下载图片保存到系统图库 private static final String pathImage = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/"; /** * 把图片网址转换为Drawable */ public static Drawable loadImageFromNetwork(String imageUrl) { Drawable drawable = null; try { // 可以在这里通过文件名来判断,是否本地有此图片 drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png"); } catch (Exception e) { Log.d("test", e.getMessage()); } // if (drawable == null) { // Log.d("test", "null drawable"); // } else { // Log.d("test", "not null drawable"); // } return drawable; } @SuppressLint("DefaultLocale") public static void saveFile(Bitmap bm, String url, Context context) throws Exception { // 判断sd卡是否存在 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // 判断文件夹是否存在 File dirFile = new File(path); if (!dirFile.exists()) { dirFile.mkdirs();//创建此抽象路径指定的目录,包括所有必须但不存在的父目录。(及可以创建多级目录,无论是否存在父目录) } String fileName = url.substring(url.lastIndexOf("/") + 1, url.length()).toLowerCase(); File file = new File(path + fileName); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); bm.compress(Bitmap.CompressFormat.PNG, 100, bos); bos.flush(); bos.close(); // //把文件插入到系统图库 // MediaStore.Images.Media.insertImage(context.getContentResolver(), bm, fileName, null); // 通知图库更新 context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file))); } else { Toast.makeText(context, context.getString(R.string.language_notSDCard), Toast.LENGTH_SHORT).show(); } }
二、保存视频到本地
1.需要导入文件下载的包
//filedownloader---Android 文件下载引擎,稳定、高效、灵活、简单易用 implementation 'com.liulishuo.filedownloader:library:1.7.3'
2.下载视频的代码
//下载视频到本地 private void downLoadVideo(String videoUrl) { FileDownloader.setup(getActivity()); final String videoName = new File(videoUrl).getName();//得到图片名称 FileDownloader.getImpl().create(videoUrl).setPath(downloadVideoPath + videoName). setForceReDownload(false)//强制重新下载,将会忽略检测文件是否健在 .setListener(new FileDownloadListener() { @Override protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) { //等待,已经进入下载队列 try { showWaitProgressDialog(getActivity(), 1, getString(R.string.language_downloading)); } catch (Exception e) { } } @Override protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) { //下载进度 } @Override protected void completed(BaseDownloadTask task) { //完成整个下载过程 try { dismissProgressDialog(); showToast(getString(R.string.language_saveSuccessfully));//退出界面时,下载完报错 // 通知图库更新 getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + downloadVideoPath + videoName))); } catch (Exception e) { } } @Override protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) { //暂停下载 } @Override protected void error(BaseDownloadTask task, Throwable e) { //下载出现错误 try { dismissProgressDialog(); showToast(getString(R.string.language_videosDownloadFail)); } catch (Exception ex) { } } @Override protected void warn(BaseDownloadTask task) { //在下载队列中(正在等待/正在下载)已经存在相同下载连接与相同存储路径的任务 } }).start(); }