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,有疑问请留言,欢迎指正错误。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。