Android选择本地图片过大程序停止的经历
最近在搞学校的创新训练项目,自己设计了个界面,通过一个按钮选择本地图片。读取较小的图片时能够顺利显示,但是读取2m的大图片时就出现程序停止运行的错误。于是在网上找到了图片压缩的方法。以下是项目中的压缩代码:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub if (resultCode != RESULT_OK) { Log.e("CODE", "ActivityResult resultCode error"); return; } if (requestCode == 1) { Uri uri = data.getData(); Bitmap bitmap = null; try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; // 节约内存 options.inPreferredConfig = Bitmap.Config.RGB_565; /* * inPurgeable如果设置为true,则由此产生的位图将分配其像素,以便系统需要回收内存时可以将它们清除; * inInputShareable与inPurgeable一起使用 ,如果inPurgeable为false那该设置将被忽略 * ,如果为true,那么它可以决定位图是否能够共享一个指向数据源的引用,或者是进行一份拷贝; */ options.inPurgeable = true; options.inInputShareable = true; // 只返回图片的大小等信息存于options中 bitmap = BitmapFactory.decodeStream(getContentResolver() .openInputStream(uri), null, options); // 获得图片的真实宽高 int height = options.outHeight; int width = options.outWidth; Log.i("path", "" + height); final float STANDARD_HEIGHT = 800f; final float STANDARD_WIDTH = 480f; // 根据需要设置inSampleSize的值 int size = (int) ((height / STANDARD_HEIGHT + width / STANDARD_WIDTH) / 2); if (size <= 0) { size = 1; } Log.i("path", "" + size); options.inSampleSize = size; // 重新设置inJustDecodeBounds = false options.inJustDecodeBounds = false; // 此时图片载入bitmap中 bitmap = BitmapFactory.decodeStream(getContentResolver() .openInputStream(uri), null, options); ImageView imgShow = (ImageView) findViewById(R.id.imgShow); imgShow.setImageBitmap(bitmap); } catch (FileNotFoundException e) { Log.e("exception", e.toString()); } super.onActivityResult(requestCode, resultCode, data); } }
图片是顺利压缩了,可是还是报程序错误,于是我想到了查看错误日志,发现一段错误日志是这样的:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/201 (has extras) }} to activity {com.example.picselecter/com.example.picselecter.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/201 from pid=19596, uid=10107 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
很明显我的程序没有赋予READ_EXTERNAL_STORAGE权限,于是加上后,程序成功运行。当然你加上WRITE_EXTERNAL_STORAGE权限也是可以的,因为它包含了READ权限。
事实证明,查看错误日志是我们定位问题的绝佳途径。