這兩天在做項目時,做到上傳圖片功能一塊時,碰到兩個問題,一個是如何獲取所選圖片的路徑,一個是如何壓縮圖片,在查了一些資料和看了別人寫的后總算折騰出來了,在此記錄一下。
首先既然要選擇圖片,我們就先要獲取本地所有的圖片,Android已經為我們封裝好了該意圖。
1 Intent intent = new Intent(Intent.ACTION_PICK, null);//從列表中選擇某項並返回所有數據 2 intent.setDataAndType( 3 MediaStore.Images.Media.EXTERNAL_CONTENT_URI,//得到系統所有的圖片 4 "image/*");//圖片的類型,image/*為所有類型圖片 5 startActivityForResult(intent, PHOTO_GALLERY);
然后我們重寫onActivityResult方法。
在Android1.5后系統會調用MediaScanner服務進行后台掃描,索引歌曲,圖片,視頻等信息,並將數據保存在android.provider.MediaStore.Images.Thumbnails 和android.provider.MediaStore.Video.Thumbnails這兩個數據庫中。
所以我們需要使用Activity.managedQuery(uri, projection, selection, selectionArgs, sortOrder)方法從數據中獲取相應數據。
uri: 需要返回的資源索引
projection: 用於標識有哪些數據需要包含在返回數據中。
selection: 作為查詢符合條件的過濾參數,類似於SQL語句中Where之后的條件判斷。
selectionArgs: 同上。
sortOrder: 對返回信息進行排序。
1 @Override 2 protected void onActivityResult(int requestCode, int resultCode, Intent data) 3 { 4 switch (requestCode) 5 { 6 //請求為獲取本地圖品時 7 case PHOTO_GALLERY: 8 { 9 //圖片信息需包含在返回數據中 10 String[] proj ={MediaStore.Images.Media.DATA}; 11 //獲取包含所需數據的Cursor對象 12 @SuppressWarnings("deprecation") 13 Cursor cursor = managedQuery(data.getData(), proj, null, null, null); 14 //獲取索引 15 int photocolumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 16 //將光標一直開頭 17 cursor.moveToFirst(); 18 //根據索引值獲取圖片路徑 19 String path = cursor.getString(photocolumn); 20 21 22 break; 23 } 24 25 default: 26 break; 27 }
以上,我們便可取得本地圖片路徑了,接下來我們隊圖片進行壓縮處理。
1 //先將所選圖片轉化為流的形式,path所得到的圖片路徑 2 FileInputStream is = new FileInputStream(path); 3 //定義一個file,為壓縮后的圖片 4 File f = new File("圖片保存路徑","圖片名稱"); 5 int size = " "; 6 Options options = new Options(); 7 options.inSampleSize = size; 8 //將圖片縮小為原來的 1/size ,不然圖片很大時會報內存溢出錯誤 9 Bitmap image = BitmapFactory.decodeStream(inputStream,null,options); 10 11 is.close(); 12 13 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 14 image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//這里100表示不壓縮,將不壓縮的數據存放到baos中 15 int per = 100; 16 while (baos.toByteArray().length / 1024 > 500) { // 循環判斷如果壓縮后圖片是否大於500kb,大於繼續壓縮 17 baos.reset();// 重置baos即清空baos 18 image.compress(Bitmap.CompressFormat.JPEG, per, baos);// 將圖片壓縮為原來的(100-per)%,把壓縮后的數據存放到baos中 19 per -= 10;// 每次都減少10 20 21 } 22 //回收圖片,清理內存 23 if(image != null && !image.isRecycled()){ 24 image.recycle(); 25 image = null; 26 System.gc(); 27 } 28 ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把壓縮后的數據baos存放到ByteArrayInputStream中 29 btout.close(); 30 FileOutputStream os; 31 os = new FileOutputStream(f); 32 //自定義工具類,將輸入流復制到輸出流中 33 StreamTransferUtils.CopyStream(btinput, os); 34 btinput.close(); 35 os.close();
完成以后,我們可以在指定的圖片保存路徑下看到壓縮的圖片。