歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android之獲取本地圖片並壓縮方法

Android之獲取本地圖片並壓縮方法

日期:2017/3/1 9:16:03   编辑:Linux編程

這兩天在做項目時,做到上傳圖片功能一塊時,碰到兩個問題,一個是如何獲取所選圖片的路徑,一個是如何壓縮圖片,在查了一些資料和看了別人寫的後總算折騰出來了,在此記錄一下。

首先既然要選擇圖片,我們就先要獲取本地所有的圖片,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: 對返回信息進行排序。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode)
{
//請求為獲取本地圖品時
case PHOTO_GALLERY:
{
//圖片信息需包含在返回數據中
String[] proj ={MediaStore.Images.Media.DATA};
//獲取包含所需數據的Cursor對象
@SuppressWarnings("deprecation")
Cursor cursor = managedQuery(data.getData(), proj, null, null, null);
//獲取索引
int photocolumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//將光標一直開頭
cursor.moveToFirst();
//根據索引值獲取圖片路徑
String path = cursor.getString(photocolumn);


break;
}

default:
break;
}

以上,我們便可取得本地圖片路徑了,接下來我們隊圖片進行壓縮處理。

//先將所選圖片轉化為流的形式,path所得到的圖片路徑
FileInputStream is = new FileInputStream(path);
//定義一個file,為壓縮後的圖片
File f = new File("圖片保存路徑","圖片名稱");
int size = " ";
Options options = new Options();
options.inSampleSize = size;
//將圖片縮小為原來的 1/size ,不然圖片很大時會報內存溢出錯誤
Bitmap image = BitmapFactory.decodeStream(inputStream,null,options);

is.close();

ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//這裡100表示不壓縮,將不壓縮的數據存放到baos中
int per = 100;
while (baos.toByteArray().length / 1024 > 500) { // 循環判斷如果壓縮後圖片是否大於500kb,大於繼續壓縮
baos.reset();// 重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, per, baos);// 將圖片壓縮為原來的(100-per)%,把壓縮後的數據存放到baos中
per -= 10;// 每次都減少10

}
//回收圖片,清理內存
if(image != null && !image.isRecycled()){
image.recycle();
image = null;
System.gc();
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把壓縮後的數據baos存放到ByteArrayInputStream中
btout.close();
FileOutputStream os;
os = new FileOutputStream(f);
//自定義工具類,將輸入流復制到輸出流中
StreamTransferUtils.CopyStream(btinput, os);
btinput.close();
os.close();

完成以後,我們可以在指定的圖片保存路徑下看到壓縮的圖片。

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved