Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發實作:呼叫系統相簿選圖並裁切

編輯:關於 Android 程式設計

「從相簿挑一張圖,順便裁一下」幾乎每個 App 都會遇到。自己刻一套選圖與裁切介面不是不行,但螢幕適配、記憶體、效能全得自己扛;直接叫用系統的在意圖(Intent)反而輕鬆又穩。以下把兩種常見做法都寫出來。

先看實際效果:

  

一、只選圖,不裁切

這種寫法只支援單選;若要多選,就得自己做,可以參考本站〈Android 編程實現仿 QQ 照片選擇器(按相冊分類顯示,多選添加)〉的源碼。

先跳轉到系統相簿:

 Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, SELECT_IMAGE); 

接著在 onActivityResult 中接回使用者選的圖,並把 Uri 還原成實體路徑:

 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != RESULT_OK || data == null) { return; } //select an image if (requestCode == SELECT_IMAGE) { //get image path from uri String imagePath = getImagePath(data.getData()); return; } } private String getImagePath(Uri selectedImage) { String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String imagePath = cursor.getString(columnIndex); cursor.close(); System.out.println("image path:" + imagePath); return imagePath; } 

二、選圖並裁切

關鍵在 Intent 上多塞幾個 extra:

 //select image via system gallery, crop and save the new image file. public void selectImageAndCrop(View view) { //After cropping, the image file will be stored here! cacheFile = imageCacheFolder + File.separator + "cache_" + System.currentTimeMillis() + ".jpg"; Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); intent.putExtra("crop", "true"); //width:height intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("output", Uri.fromFile(new File(cacheFile))); intent.putExtra("outputFormat", "JPEG"); startActivityForResult(Intent.createChooser(intent, "Choose Image"), SELECT_IMAGE_CROP); } 

三個 extra 各自的作用:

(1)crop:傳 true,告訴系統「我要裁切」。
(2)aspectX 與 aspectY:裁切框的寬高比。
(3)output:以 cacheFile 建出來的 Uri。使用者選完圖會自動進入裁切頁,裁完的結果就落在這個檔案位置。

流程走完一樣回到 onActivityResult,此時直接讀 cacheFile 即可,例如塞進 ImageView:

 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != RESULT_OK) { return; } //select an image and crop if (requestCode == SELECT_IMAGE_CROP) { //compress the original image to save memory. BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inSampleSize = 4; imageView.setImageBitmap(BitmapFactory.decodeFile(cacheFile, opt)); } } 

最後提醒:inSampleSize 這類取樣參數別省,手機解析度動輒上千萬像素,不做降採樣很容易直接 OOM。

更多 Android 相關內容有興趣的讀者可查看本站專題:《Android圖形與圖像處理技巧總結》、《Android開發入門與進階教程》、《Android調試技巧與常見問題解決方法匯總》、《Android基本組件用法總結》、《Android視圖View技巧總結》、《Android布局layout技巧總結》及《Android控件用法總結》

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved