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")
@Override
protected 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 file
if (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 button
if (isCancelled())
return null;
total += count;
if (fileLength > 0) // only if total length is known
publishProgress((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;
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.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));
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.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")
@Override
protected 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 file
if (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 button
if (isCancelled())
return false;
total += count;
if (fileLength > 0) // only if total length is known
publishProgress((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();
}
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.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));
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.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,有疑问请留言,欢迎指正错误。
Android保存图片到本地相册的更多相关文章
- 微信小程序点击保存图片到本地相册——踩坑
在微信小程序中要保存图片到本地相册,需要获取相册权限. 总之整个功能实现下来需要如下几个小程序的API:wx.getSetting,wx.authorize,wx.openSetting,wx.dow ...
- iOS-iOS调用相机调用相册【将图片保存到本地相册】
设置头部代理 <UINavigationControllerDelegate, UIImagePickerControllerDelegate> 1.调用相机 检测前置摄像头是否可用 - ...
- 史上最强Android 开启照相或者是从本地相册选中一张图片以后先裁剪在保存并显示的讲解附源码
整个程序的布局很简单 只在一个垂直方向上的线性布局里面有俩个按钮(Button)和一个显示图片的控件(ImageView)这里就不给出这部分的代码了 1.是打开系统的相册 Intent alb ...
- React Native之图片保存到本地相册(ios android)
React Native之图片保存到本地相册(ios android) 一,需求分析 1,react native保存网络图片到相册,iOS端可以用RN自带的CameraRoll完美解决,但是andr ...
- Android:支持多选的本地相册
前段时间在做一个动态发布功能,需要用到图片上传.一开始直接调用的系统相册和相机,由于系统相机不支持多选,就花点时间做了个本地相册,在此开源下. 先上截图,依次为选择相册界面.相册详情界面.查看图片大图 ...
- Android中通过访问本地相册或者相机设置用户头像
目前几乎所有的APP在用户注册时都会有设置头像的需求,大致分为三种情况: (1)通过获取本地相册的图片,经过裁剪后作为头像. (2)通过启动手机相机,现拍图片然后裁剪作为头像. (3)在APP中添加一 ...
- Xamarin.Android 调用本地相册
调用本地相册选中照片在ImageView上显示 代码: using System; using System.Collections.Generic; using System.Linq; using ...
- Android获取本地相册图片、拍照获取图片
需求:从本地相册找图片,或通过调用系统相机拍照得到图片. 容易出错的地方: 1,当我们指定了照片的uri路径,我们就不能通过data.getData();来获取uri,而应该直接拿到uri(用全局变量 ...
- Android笔记之使用ImageView加载网络图片以及保存图片到本地并更新图库
ImageView显示网络图片 findViewById(R.id.btnLoad).setOnClickListener(new View.OnClickListener() { @Override ...
随机推荐
- ubuntu 系统 更改屏幕亮度为最大(15级亮度)
历经千辛万苦终于搞定屏幕亮度,现将成果分享如下. 硬件:联想K29 系统:UBUNTU 14.04 一.执行命令 sudo gedit /etc/default/grub 二.更改文本 然后找到 GR ...
- [转] .NET领域驱动设计—初尝(疑问、模式、原则、工具、过程、框架、实践)
阅读目录: 1.1.疑问 1.1.1.UML何用 1.1.2.领域建模 1.2.模式 1.3.原则 1.5.过程 1.6.框架 1.7.项目演示 最近在研究DDD颇有收获,所以整理出来跟大家分享,共同 ...
- php session_start()报错 解决办法
1.php.ini中的output_buffering=off 改成output_buffering=4096 2.php.ini中的session.save_path是否设置好了 3.php.ini ...
- LVS工作模式与调度算法
LVS三种工作模式.十种调度算法介绍 工作模式介绍: 1.Virtual server via NAT(VS-NAT) 优点:集群中的物理服务器可以使用任何支持TCP/IP操作系统,物理服务器可以分配 ...
- 分享几个 git 的使用场景
你真的会使用 git 吗?你能回答下面几个问题吗? 有三个commit(顺序:CommitA.CommitB.CommitC),它们相互独立,没有依赖. 在不修改B.C的前提下,修改A,怎么操作? 合 ...
- PHP基础入门(五)---PHP面向对象
前言: 今天来和大家介绍一下PHP的面向对象.说到面向对象,我不得不提一下面向过程,因为本人在初学时,常常分不清楚. 那么面向对象和面向过程有什么区别呢?下面给大家简单介绍一下: 面向对象专注于由哪个 ...
- Vivo展柜灯怎样设计才吸引大量客户?
1.vivo展柜灯计划的目标是使消耗者在无限的时空中最无效地承受信息.因而,vivo展柜灯计划便是围绕着怎样无效地进步展现活动的服从和质量停止的.除了展现环境本身的计划之外,展现对象陈列方式的计划也是 ...
- 前端解读Webview
作为盛行已久的开发方式,Hybrid的相关介绍已经是相当普遍了.不过看到博客园里基本上都是从android或者ios的角度来讲解的,对于h5的前端来说看起来只能是一直半解.感觉有必要从前端的角度来理解 ...
- 超好用的memcache管理及可视化监控工具,真方便!
memcache做为主流的缓存数据库之一,广泛在各互联网平台使用,但是大家使用中都知道memcache目前没有一个比较好用的可视化客户端工具,每次都要输入命令进行操作,十分不方便. 而另一款主流缓存 ...
- Linux内核的基本概念
Linux内核学习,推荐的书籍: <linux设备驱动开发详解第二版>.<Linux内核设计与实现第三版>.<嵌入式Linux应用开发完全手册> 第一篇:讲解Lin ...