Android保存图片到本地相册
生活随笔
收集整理的這篇文章主要介紹了
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保存图片到本地相册的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: POJ 1330 LCA最近公共祖先 离
- 下一篇: tiny xml 使用总结