Android保存图片到本地相册
好久没有写东西了。备份下知识吧。免得忘记了 。
首先贴一段代码 -- 这个是先生成一个本地的路径,将图片保存到这个文件中,然后扫描下sd卡。让系统相册重新加载下 。缺点就是只能保存到DCIM的文
件夹下边,暂时不知道怎么获取系统相机的路径,网上找了下说了好几个方法。其中有一条就是去读取本地的图片,然后根据一定的规则识别出本地相册的路径
保存下,不过觉得性能不是很好。谁有更好的方法可以提供下。
private class DownloadTask extends AsyncTask<String, Integer, String> {private Context context;private String filepath;public int fileLength = 0; public DownloadTask(Context context) {this.context = context;File cacheDir = new File(ImageLoader.getExternalCacheDir(context).getAbsolutePath() );if(!cacheDir.exists()) {cacheDir.mkdirs();}
// filepath = ImageLoader.getExternalCacheDir(context).getAbsolutePath() + File.separator + "caihongjiayuan.jpg";filepath = UIUtils.generateDownloadPhotoPath();}@SuppressWarnings("resource")@Overrideprotected String doInBackground(String... sUrl) {PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());wl.acquire();InputStream input = null;OutputStream output = null;HttpURLConnection connection = null;try {URL url = new URL(sUrl[0]);connection = (HttpURLConnection) url.openConnection();connection.setConnectTimeout(5000);connection.setReadTimeout(20000);connection.connect();// expect HTTP 200 OK, so we don't mistakenly save error report// instead of the fileif (connection.getResponseCode() != HttpURLConnection.HTTP_OK)return "Server returned HTTP " + connection.getResponseCode() + " "+ connection.getResponseMessage();fileLength = connection.getContentLength();input = connection.getInputStream();output = new FileOutputStream(filepath);byte data[] = new byte[4096];long total = 0;int count;while ((count = input.read(data)) != -1) {// allow canceling with back buttonif (isCancelled())return null;total += count;if (fileLength > 0) // only if total length is knownpublishProgress((int)total);output.write(data, 0, count);}} catch (Exception e) {return null;} finally {try {if (output != null)output.close();if (input != null)input.close();} catch (IOException ignored) {}if (connection != null)connection.disconnect();wl.release();}return filepath;}@Overrideprotected void onProgressUpdate(Integer... values) {// TODO Auto-generated method stubsuper.onProgressUpdate(values);float progress = (float)values[0]/(float)fileLength;mProgressInfo.setText(getString(R.string.download_progress_info,StringUtils.getKBUnitString(values[0]),StringUtils.getKBUnitString(fileLength)));mProgressBar.setProgress((int)(progress * 100));}@Overrideprotected void onPostExecute(String result) {// TODO Auto-generated method stubsuper.onPostExecute(result);mDownloadView.setVisibility(View.GONE);if (!TextUtils.isEmpty(result)) {ImageUtils.scanFile(mCurrentActivity, filepath);ToastUtils.showLongToast(mCurrentActivity, mCurrentActivity.getString(R.string.tips_img_save_path, filepath));}else {ToastUtils.showLongToast(mCurrentActivity, R.string.tips_download_photo_faile);}//
// Bitmap bitmap = BitmapFactory.decodeFile(filepath);
// boolean flag = ImageUtils.insertImageToAllbum(bitmap, mCurrentActivity);
// if (flag) {ToastUtils.showLongToast(mCurrentActivity, R.string.tips_download_photo_success);
// }else {
// ToastUtils.showLongToast(mCurrentActivity, R.string.tips_download_photo_faile);
// }}}
参考了下别的文章,找到下边一个方法能解决大部分机型适配的问题,且可以将照片保存到系统相机拍完照的目录下。供大家参考。
private class DownloadTask extends AsyncTask<String, Integer, Boolean> {private Context context;public int fileLength = 0;private Bitmap bmp; public DownloadTask(Context context) {this.context = context;File cacheDir = new File(ImageLoader.getExternalCacheDir(context).getAbsolutePath() );if(!cacheDir.exists()) {cacheDir.mkdirs();}}@SuppressWarnings("resource")@Overrideprotected Boolean doInBackground(String... sUrl) {PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());wl.acquire();InputStream input = null;ByteArrayOutputStream output = null;HttpURLConnection connection = null;try {URL url = new URL(sUrl[0]);connection = (HttpURLConnection) url.openConnection();connection.setConnectTimeout(5000);connection.setReadTimeout(20000);connection.connect();// expect HTTP 200 OK, so we don't mistakenly save error report// instead of the fileif (connection.getResponseCode() != HttpURLConnection.HTTP_OK)return false;fileLength = connection.getContentLength();input = connection.getInputStream();output = new ByteArrayOutputStream();byte data[] = new byte[4096];long total = 0;int count;while ((count = input.read(data)) != -1) {// allow canceling with back buttonif (isCancelled())return false;total += count;if (fileLength > 0) // only if total length is knownpublishProgress((int)total);output.write(data, 0, count);}bmp = BitmapFactory.decodeByteArray(output.toByteArray(),0 , output.toByteArray().length);return true;} catch (Exception e) {return false;} finally {try {if (output != null)output.close();if (input != null)input.close();} catch (IOException ignored) {}if (connection != null)connection.disconnect();wl.release();}}@Overrideprotected void onProgressUpdate(Integer... values) {// TODO Auto-generated method stubsuper.onProgressUpdate(values);float progress = (float)values[0]/(float)fileLength;mProgressInfo.setText(getString(R.string.download_progress_info,StringUtils.getKBUnitString(values[0]),StringUtils.getKBUnitString(fileLength)));mProgressBar.setProgress((int)(progress * 100));}@Overrideprotected void onPostExecute(Boolean result) {// TODO Auto-generated method stubsuper.onPostExecute(result);mDownloadView.setVisibility(View.GONE);if (result.booleanValue() && ImageUtils.insertImageToAllbum(bmp, mCurrentActivity)) {}else {ToastUtils.showLongToast(mCurrentActivity, R.string.tips_download_photo_faile);}}}
两个方法的区别就是将FileOutputStream换成了ByteArrayOutputStream项目中主要是有显示下载进度条的需求,所以稍微复杂了点。
另外: ImageUtils 中insertImage 方法如下。
public static boolean insertImageToAllbum(Bitmap bitmap,Context mContext) {if (bitmap != null) {String uri = MediaStore.Images.Media.insertImage(mContext.getContentResolver(),bitmap, "", "");if (!TextUtils.isEmpty(uri)) {String filePath = getRealPathFromURI(Uri.parse(uri),mContext);ToastUtils.showLongToast(mContext, mContext.getString(R.string.tips_img_save_path, filePath));scanFile(mContext,filePath);return true;}}return false;}public static void scanFile(Context mContext,String path){MediaScannerConnection.scanFile(mContext, new String[] { path }, null,new MediaScannerConnection.OnScanCompletedListener() {public void onScanCompleted(String path, Uri uri) {}});}
方法scanFile是让系统重新加载SD卡的 。。
over,有疑问请留言,欢迎指正错误。
转载于:https://www.cnblogs.com/gengsy/p/3905023.html
Android保存图片到本地相册相关推荐
- android 6.0获取图片地址,Android应用开发Android 保存图片到系统相册(三星6.0有效)...
Android 保存图片到系统相册(三星6.0有效).今天要做一个保存图片到系统图库的功能,自身能力较浅,所以只能搜索了但发现网上的方法有几处bug,所以自己总结一下防止以后忘掉也想和大家分享一下 ...
- uni-app保存图片到本地相册
犯了一个白痴问题,引用的图片都是本地的,下载拿到的临时路径无法保存,换成网络路径就好了. uni-app移动端保存图片到本地相册 uni-app中有一个接口:uni.saveImageToPhotos ...
- h5 /web 手机端 实现保存图片 到本地相册 uni-app
文章目录 首先,必须得知道的事情是: uni-app中是有保存图片到本地相册的api的:但是h5并不适用 手机浏览器长按图片会出现保存图片的按钮直接进行保存图片,甚至在微信中还可以进行扫一扫 H5Pl ...
- uni-app 保存图片到本地相册
uni-app 保存图片到本地相册页面 <image @longpress="saveimg()" src="../../static/image/1.jpg&qu ...
- android webview打开相册,Android WebView调用本地相册的方法
本文实例为大家分享了Android WebView调用本地相册的具体实现方法,供大家参考,具体内容如下 首先要知道android本身的WebView是并不支持调用手机文件并上传的,其次WebView的 ...
- uni-app移动端保存图片到本地相册
uni-app移动端保存图片到本地相册 uni-app中有一个接口:uni.saveImageToPhotosAlbum,但是之前使用的时候,真机测试没有问题,但是打了安装包就保存失败,走的是fail ...
- Android 保存图片到本地
现在项目中基本都有这样的需求,把图片保存到本地相册 这是一个工具类代码如下: public class ImgUtils {/*** 保存文件到指定路径*/public static boolean ...
- Android保存图片到系统相册
先说一下思路,我是这样做的,先保存一张图片到可写路径下,用cocos2d的节点截屏功能,保存之后就可以 保存Bitmap到本地指定路径下 ,然后通过广播,通知系统相册图库刷新数据. 先说如何节点截屏: ...
- android 系统相册 多远,【系统相册】Android 保存图片到系统相册
保存完图片后,可以在内存设备的文件系统相册目录下看到对应图片(以小米手机为例,系统相册的路径为:/storage/emulated/0/DCIM/Camera).但是,使用系统图库无法马上看到该图片, ...
最新文章
- asp.net Core多环境读取Json
- Oracle RAC 环境下的连接管理
- Java程序猿必读的书籍,良心推荐!
- SQL AVG() 函数
- 自动提醒IE6访客升级浏览器,
- 番石榴15 –新功能
- 数据库操作php,一个数据库操作PHP类
- Python数据分析实战:使用pyecharts进行数据可视化
- 数据开放 数据集_您可以使用开放数据做什么?
- oracle 数据补齐月份,Oracle自定义函数--增加月份
- MATLAB信号与系统分析(三)——连续信号与系统的复频域分析及MATLAB实现
- 【Python简明教程一】Python编程基础
- 金洪林:红邦创衣止于至善_品牌-生活时尚_品牌_YOKA时尚网
- java echarts 柱形图数字显示在顶部
- [PPTX解析] 图片效果算法篇:设置透明色
- 【矩阵论笔记】最小多项式与Jordan型的关系
- 教你怎样用最少的钱拍出最美的婚纱
- 《大话数据结构》读书笔记(二)
- Windows快捷键操作
- 冥冥中的感觉,是梦非梦
热门文章
- visual studio 2019 未能在命名空间“System.IO.Ports”中找到类型名“SerialPort”
- php apache win7,win7安装apache+php
- 图像分割-二阶导数零交叉点的含义
- 操作系统磁盘调度_磁盘调度| 操作系统
- kotlin 计算平方_Kotlin程序计算自然数之和
- Java SimpleTimeZone setEndRule()方法与示例
- 物联网基础知识_联网| 基础知识能力问答 套装1
- PyCharm安装及配置
- 计算机数学基础模拟试题,计算机数学基础》模拟考试试题.doc
- centos 6.8安装git_RPM包的卸载与安装,包含依赖包卸载