轉載聲明:Ryan的部落格文章歡迎您的轉載,但在轉載的同時,請注明文章的來源出處,不勝感激! :-)
http://blog.csdn.net/floodingfire/article/details/8144615
在這篇部落格中,我将向大家展示如何從相冊截圖。
上一篇部落格中,我就拍照截圖這一需求進行了詳細的分析,試圖讓大家了解Android本身的限制,以及我們應當采取的實作方案。
根據我們的分析與總結,圖檔的來源有拍照和相冊,而可采取的操作有
前面我們了解到,使用Bitmap有可能會導緻圖檔過大,而不能傳回實際大小的圖檔,我将采用大圖Uri,小圖Bitmap的資料存儲方式。
我們将要使用到URI來儲存拍照後的圖檔:
1 | private static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg" ;//temp file |
2 | Uri imageUri = Uri.parse(IMAGE_FILE_LOCATION); //The Uri to store the big bitmap |
不難知道,我們從相冊選取圖檔的Action為Intent.ACTION_GET_CONTENT。
根據我們上一篇部落格的分析,我準備好了兩個執行個體的Intent。
一、從相冊截大圖:
01 | Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null ); |
02 | intent.setType( "image/*" ); |
03 | intent.putExtra( "crop" , "true" ); |
04 | intent.putExtra( "aspectX" , 2 ); |
05 | intent.putExtra( "aspectY" , 1 ); |
06 | intent.putExtra( "outputX" , 600 ); |
07 | intent.putExtra( "outputY" , 300 ); |
08 | intent.putExtra( "scale" , true ); |
09 | intent.putExtra( "return-data" , false ); |
10 | intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); |
11 | intent.putExtra( "outputFormat" , Bitmap.CompressFormat.JPEG.toString()); |
12 | intent.putExtra( "noFaceDetection" , true ); // no face detection |
13 | startActivityForResult(intent, CHOOSE_BIG_PICTURE); |
二、從相冊截小圖
01 | Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null ); |
02 | intent.setType( "image/*" ); |
03 | intent.putExtra( "crop" , "true" ); |
04 | intent.putExtra( "aspectX" , 2 ); |
05 | intent.putExtra( "aspectY" , 1 ); |
06 | intent.putExtra( "outputX" , 200 ); |
07 | intent.putExtra( "outputY" , 100 ); |
08 | intent.putExtra( "scale" , true ); |
09 | intent.putExtra( "return-data" , true ); |
10 | intent.putExtra( "outputFormat" , Bitmap.CompressFormat.JPEG.toString()); |
11 | intent.putExtra( "noFaceDetection" , true ); // no face detection |
12 | startActivityForResult(intent, CHOOSE_SMALL_PICTURE); |
三、對應的onActivityResult可以這樣處理傳回的資料
01 | switch (requestCode) { |
02 | case CHOOSE_BIG_PICTURE: |
03 | Log.d(TAG, "CHOOSE_BIG_PICTURE: data = " + data); //it seems to be null |
04 | if (imageUri != null ){ |
05 | Bitmap bitmap = decodeUriAsBitmap(imageUri); //decode bitmap |
06 | imageView.setImageBitmap(bitmap); |
09 | case CHOOSE_SMALL_PICTURE: |
11 | Bitmap bitmap = data.getParcelableExtra( "data" ); |
12 | imageView.setImageBitmap(bitmap); |
14 | Log.e(TAG, "CHOOSE_SMALL_PICTURE: data = " + data); |
01 | private Bitmap decodeUriAsBitmap(Uri uri){ |
02 | Bitmap bitmap = null ; |
04 | bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri)); |
05 | } catch (FileNotFoundException e) { |
效果圖:
大圖 | 小圖 |
| |
基礎篇:
【譯】如何使用Android MediaStore裁剪大圖檔
上篇:
Android大圖檔裁剪終極解決方案(上:原理分析)
中篇:
Android大圖檔裁剪終極解決方案(中:從相冊截圖)
下篇:
Android大圖檔裁剪終極解決方案(下:拍照截圖)