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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/399150.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

PHP的钩子实现解析

2019独角兽企业重金招聘Python工程师标准>>> 钩子是编程里一个常见概念&#xff0c;非常的重要。它使得系统变得非常容易拓展&#xff0c;&#xff08;而不用理解其内部的实现机理&#xff0c;这样可以减少很多工作量&#xff09;。只要有一个钩子样本&#xff0c;能…

writer在java中的意思_Java在FileWriter和BufferedWriter之间的区别

小编典典如果您使用BufferedWriter则效率更高在刷新/关闭之间有多次写入与缓冲区大小相比&#xff0c;写操作较小。在您的示例中&#xff0c;您只有一次写入&#xff0c;因此BufferedWriter只会增加您不需要的开销。这是否意味着第一个示例一个接一个地写入字符&#xff0c;第二…

Ubuntu配置静态IP

进入 /etc/network/interfaces&#xff0c;修改成如下&#xff1a; # interfaces(5) file used by ifup(8) and ifdown(8)auto loiface lo inet loopbackauto ens33iface ens33 inet staticaddress 192.168.1.110netmask 255.255.255.0gateway 192.168.1.1dns-nameserver 8.8.8…

tiny xml 使用总结

这几天在埋头写自己的3D文件浏览器&#xff08;稍后发布&#xff09;&#xff0c;突发奇想的要把自己的内部格式转化成XML&#xff0c;于是&#xff0c;把以前在研究所时用过的ExPat翻了出来。ExPat是基于事件的XML解释器&#xff0c;速度挺快的&#xff0c;但结构方面有点不敢…

Beta冲刺! Day2 - 砍柴

Beta冲刺&#xff01; Day2 - 砍柴 今日已完成 晨瑶&#xff1a;大致确定了文章推荐的算法思路&#xff08;Content-based recommender&#xff09;&#xff1b;理清了不少feature的事宜昭锡&#xff1a;修复了日期选择越界时导致程序崩溃和点击光点返回后&#xff0c;日期选择…

Android版添加phonegap--websocket客户端插件教程

2019独角兽企业重金招聘Python工程师标准>>> 1.在Eclipse中新建Android Project项目chatdemo2.把animesh kumar的websocket-android-phonegap项目java文件打成phonegap-websocket-support.jar包&#xff0c;存放在 android project的libs目录下3.把websocket.js存放…

java参数传入的是一个类名_Java编程细节——泛型的定义(类、接口、对象)、使用、继承...

1. 设计泛型的初衷&#xff1a;1) 主要是为了解决Java容器无法记忆元素类型的问题&#xff1a;i. 由于Java设计之初并不知道会往容器中存放什么类型的元素&#xff0c;因此元素类型都设定为Object&#xff0c;这样就什么东西都能放了&#xff01;ii. 但是这样设计有明显的缺点&…

ExtJS Grid Column Number

{xtype: numbercolumn,text: 亏盈数量,width: 130,dataIndex: LossOrProfitNum,editor: {xtype: numberfield,minValue: 0,decimalPrecision: 2},renderer: function (value, cellmeta) {return Ext.util.Format.number(value, 0.00);}}转载于:https://www.cnblogs.com/denghua…

#define | enum(enumerator)

/***************************************************************************** #define | enum(enumerator)* 声明&#xff1a;* 今天突然在Linux内核看到枚举和宏&#xff0c;感觉是一样的功能&#xff0c;于是找了一下他们* 之间差异。** …

网页制作中如何自定义网页图标

第一步&#xff0c;准备一个图标制作软件。 首先您必须了解所谓的图标&#xff08;Icon&#xff09;是一种特殊的图形文件格式&#xff0c;它是以.ico 作为扩展名。普通的图像设计软件无法使用这种格式&#xff0c;所以您需要到下载一个ico图标工具,本站常用软件既有,推荐强大…

ext 解析后台返回response.responseText中的数据

Ext.Ajax.request({ url: "...", method: "POST", params: { currentID: mainNode.attributes.id }, success: function (response) { var resp Ext.decode(response.responseText )&#xff1b; resp.totalCount; } }); //ajax over //响应中返回的resp…

java资源争夺_所有满足类似需求,争夺同类资源的组织和个人统称为(   )。...

【判断题】重合断面的轮廓线用细实线绘制。【单选题】阿萨德法师法啥【单选题】三相桥式交叉连接电路为限制脉动环流需要( )平衡电抗器【单选题】地方搞活动风格化大发光火【填空题】若s是int型变量,且s6,则表达式s%2(s1)%2的值为________。【填空题】负反馈的作用是( )。【单选…

Linux环境下安装部署AWStats日志分析系统实例

AWStats是使用Perl语言开发的一款开放性日志分析系统&#xff0c;可分析Apache网站服务器的访问日志&#xff0c;还可以用来分析Samba、Vsftpd、IIS等日志信息。此文章主要讲解如何在linux系统下安装部署关于对Apache网站服务站日志分析的AWStats。实验步骤一&#xff0c;安装部…

HDU4911 Inversion 解题报告

题意&#xff1a;求逆序对 解题思路&#xff1a;1)树状数组 离散化 解题代码&#xff1a; 1 // File Name: a.cpp2 // Author: darkdream3 // Created Time: 2014年08月05日 星期二 12时05分09秒4 5 #include<vector>6 #include<list>7 #include<map>8 #inc…

springmvc的国际化

1&#xff1a;三个国际化资源文件 i18n.usernameUsername i18n.passwordPassword i18n.username\u7528\u6237\u540D i18n.password\u5BC6\u7801 i18n.usernameUsername i18n.passwordPassword 2&#xff1a;在spring中配置国际化资源文件 <!-- 配置国际化资源文件 --><…

java逻辑编程题_50道经典Java逻辑编程题白岩山

光棍节英语-2021年1月21日发(作者&#xff1a;卞敏)【程序1】题目&#xff1a;古典问题&#xff1a;有一对兔子&#xff0c;从出生后第3个月起每个月都生一对兔子&#xff0c;小兔子长到第三个月后每个月又生一对兔子&#xff0c;假如兔子都不死&#xff0c;问每个月的兔子总数…

.9-浅析webpack源码之NodeEnvironmentPlugin模块总览

介绍Compiler的构造比较无趣&#xff0c;不如先过后面的&#xff0c;在用到compiler的时候再做讲解。 这一节主要讲这行代码&#xff1a; // 不管这里 compiler new Compiler(); compiler.context options.context; compiler.options options; // 看这里 new NodeEnvironmen…

运行QQ出现initialization failure 0x0000000c错误和浏览器上不了网

出现QQ出现initialization failure 0x0000000c错误和浏览器上不了网的问题&#xff0c;原因是关机的时候没有正常关闭导致的。 解决方法&#xff1a; 1、我们在开始菜单栏中的附件中找到“命令提示符”&#xff0c;然后点击右键选择“以管理员身份运行”。 或者windowx&#xf…

Unity3D 动态加载 图片序列正反播放

参考来源 跟来源的电子图书翻页多了点细节上的变化。 using UnityEngine; using System.Collections; using System.Resources;public class MovePic : MonoBehaviour {public Texture2D[] texAll; //图片序列储存的图片组&#xff0c;注意需要定义这个组的size大小为图片序列…

【IT笔试面试题整理】寻找二叉树两节点的最近的公共祖先

【试题描述】 求二叉树中任意两个节点的最近公共祖先也称为LCA问题&#xff08;Lowest Common Ancestor&#xff09;。 二叉查找树 如果该二叉树是二叉查找树&#xff0c;那么求解LCA十分简单。 基本思想为&#xff1a;从树根开始&#xff0c;该节点的值为t&#xff0c;如果t大…