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保存图片到本地相册

时间: 2024-08-02 07:52:20

Android保存图片到本地相册的相关文章

android保存图片到本地并可以在相册中显示出来

app应用是越来越人性化:界面优美,服务多样化,操作还非常方便.比如我们在用app的时候,发现上面有比较的图片想保存到手机,只要点一点app上提供的保存按钮就可以了.那这个图片保存到本地怎么实现的呢? 保存图片很简单,方法如下: /** 首先默认个文件保存路径 */ private static final String SAVE_PIC_PATH=Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_M

iOS开发-iOS调用相机调用相册【将图片保存到本地相册】

设置头部代理 <UINavigationControllerDelegate, UIImagePickerControllerDelegate> 1.调用相机 检测前置摄像头是否可用 - (BOOL)isFrontCameraAvailable{ return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]; } 检测后置摄像头是否可用 - (BOOL)isRe

史上最强Android 开启照相或者是从本地相册选中一张图片以后先裁剪在保存并显示的讲解附源码

整个程序的布局很简单 只在一个垂直方向上的线性布局里面有俩个按钮(Button)和一个显示图片的控件(ImageView)这里就不给出这部分的代码了 1.是打开系统的相册 Intent albumIntent = new Intent(Intent.ACTION_PICK, null); albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityFo

Android中通过访问本地相册或者相机设置用户头像

目前几乎所有的APP在用户注册时都会有设置头像的需求,大致分为三种情况: (1)通过获取本地相册的图片,经过裁剪后作为头像. (2)通过启动手机相机,现拍图片然后裁剪作为头像. (3)在APP中添加一些自带的头像资源,供用户选择(不够人性化,目前很少使用). 这次我们简单介绍下通过获取本地相册以及相机拍摄的方法设置头像,实现思路如下: (1)通过startActivityForResult方法,分别传递调用系统相册的Intent和调用相机拍照的Intent来做选择 (2)调用Android系统中

Android:支持多选的本地相册

前段时间在做一个动态发布功能,需要用到图片上传.一开始直接调用的系统相册和相机,由于系统相机不支持多选,就花点时间做了个本地相册,在此开源下. 先上截图,依次为选择相册界面.相册详情界面.查看图片大图界面    相册列表按图片数量降序排序,相册详情列表按图片时间降序排序,对比了下微信和QQ的相册,读取的文件基本一致. 接下来说下相册文件遍历的思路.首先肯定不会是通过文件夹逐级遍历的,这样效率太低.查了下API发现Android的系统数据库已经存储了所有的图片路径和缩略图路径(如果有),可直接通过

Android设置头像,手机拍照或从本地相册选取图片作为头像

 [Android设置头像,手机拍照或从本地相册选取图片作为头像] 像微信.QQ.微博等社交类的APP,通常都有设置头像的功能,设置头像通常有两种方式: 1,让用户通过选择本地相册之类的图片库中已有的图像,裁剪后作为头像. 2,让用户启动手机的相机拍照,拍完照片后裁剪,然后作为头像. 我现在写一个简单的完整代码例子,说明如何在Android中实现上述两个头像设置功能. MainActivity.java文件: package zhangpgil.photo; import java.io.F

Android获取本地相册图片、拍照获取图片

需求:从本地相册找图片,或通过调用系统相机拍照得到图片. 容易出错的地方: 1,当我们指定了照片的uri路径,我们就不能通过data.getData();来获取uri,而应该直接拿到uri(用全局变量或者其他方式)然后设置给imageView imageView.setImageURI(uri); 2,我发现手机前置摄像头拍出来的照片只有几百KB,直接用imageView.setImageURI(uri);没有很大问题,但是后置摄像头拍出来的照片比较大,这个时候使用imageView.setIm

android平台 cocos2d-x 读取相册数据

现已解决 方案如下:1.使用 jni 调用 java 方法 启动相册选择框2.使用java将获取的图片保存到本地3.使用Cocos2d-x中 CCImage 读取JAVA代码如下:    //启动图片选择框      private void launchCamera()      {          // TODO Auto-generated method stub          Intent intent = new Intent();          intent.setType

iOS--将图片保存至本地相册

今天做聊天,领导说对方给我发一个图片,我要保存到本地,IOS的UIKit Framework提供了UIImageWriteToSavedPhotosAlbum方法对图像进行保存,该方法会将image保存至用户的相册中: 上代码: void UIImageWriteToSavedPhotosAlbum ( UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo ); 参数说明: image : 需