Android儲存圖片到本地相簿

來源:互聯網
上載者:User

標籤:android   style   blog   http   color   java   os   io   

好久沒有寫東西了。備份下知識吧。免得忘記了 。

首先貼一段代碼 --  這個是先產生一個本地的路徑,將圖片儲存到這個檔案中,然後掃描下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,有疑問請留言,歡迎指正錯誤。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.