Android之获取本地图片并压缩方法
这两天在做项目时,做到上传图片功能一块时,碰到两个问题,一个是如何获取所选图片的路径,一个是如何压缩图片,在查了一些资料和看了别人写的后总算折腾出来了,在此记录一下。
首先既然要选择图片,我们就先要获取本地所有的图片,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();
完成以后,我们可以在指定的图片保存路径下看到压缩的图片。