使用内置Camera捕获图片并加载
Camera应用程序在其清单文件中指定了以下意图过滤器。
<intent-filter> <action android:name="android.media.action.IMAGE_CAPTURE"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter>
通过意图利用Camera程序,我们所要做的仅仅是必须构造一个将由上述过滤器捕获的意图就可以了。
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
在实践中, 这个字符串在未来可能发行量的,所以我们指定MediaStore类中的常量ACTION_IMAGE_CAPTURE比使用字符串更有利于未来的变化。
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
如果使用startActivity(intent);
那Camer应用程序没有将图片返回给调用活动,那我们调用就没有任何作用。
所以我们应使用
startActivityForResult(intent, 0); //通过重写Activity中的onActivityResult方法得到想要的数据 @Override protected void onActivityResult(int arg0, int arg1, Intent arg2) {//得到Camera返回的数据 // TODO Auto-generated method stub super.onActivityResult(arg0, arg1, arg2); if(arg1 == RESULT_OK){ Bundle extra = arg2.getExtras();//从意图中得到附加值 Bitmap bmp = (Bitmap) extra.get("data");//从附加值中获取返回的图像
iv.setImageBitmap(bmp);
}
}
当运行时你会发现现返回的显示图片很小,宽为121px,高为162px(不同设备会有所不同)。这是一张经过处理过再返回的小图片。
Camera应用程序不会将全尺寸的图像返回给主调活动。因为会需要大量的内存,而移动设备一般会在内存方面受限,所以Camera应用程序将在返回的图片中返回
一幅很小的缩略图。
为了捕获更大的图像,我们可以将一个附加值传递给触发Camera应用程序的意图。这个附加值的名称在MediaStore类中指定,它是一个常量,EXTRA_OUTPUT。
这个附加值将以URI的方式指示Camera应用程序您想要的捕获的图像保存在什么位置。
如:
String imageFilePath = Environment.getExternalStorageDirectory(). getAbsolutePath()+"myfavoritepicture.jpg"; File imageFile = new File(imageFilePath); Uri imageFileUri = Uri.fromFile(imageFile); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri); startActivityForResult(intent, 0);
这样你就可以在你指定的位置看到你所拍的那张图片
而、如果你想要显示这张大图像,那你要做一些相对应的处理,为了程序的使用性和稳定性或
以防加载图像过大而导致内存不足,或出现内存溢出状态
BitmapFactory应用程序类提供了一系列的静态方法,允许通过各种来源加载Bitmap图像。
可以通过BitmapFactory.Options中指定inSampleSize参数指定图片缩放比例。
比如缩放1/8
BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inSampleSize = 8; Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, opts); iv.setImageBitmap(bmp);
这是一种快速加载大图像的方法,而没有考虑图像的原始大小和考虑屏幕大小。
在实践中我们需要考虑到图像的原始大小和使用设备的屏幕大小
//获取屏幕大小 Display display = getWindowManager().getDefaultDisplay(); int dw = display.getWidth(); int dh = display.getHeight(); BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true;//解析图像但不加载图像,设置了此参数为true, //则只解析图像,得到各个参数而不会把图像加载到内存 Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, opts); //得到比例 int heightRatio = (int) Math.ceil(opts.outHeight/(float)dh); int widthRatio = (int) Math.ceil(opts.outWidth/(float)dw); //如果有一个比例大于1 //那么进行缩放 if(heightRatio > 1 || widthRatio > 1){ if(heightRatio > widthRatio){ //如果高度比率大,则根据它绽放 opts.inSampleSize = heightRatio; }else{ //如果宽度比率大,则根据它缩放 opts.inSampleSize = widthRatio; } } opts.inJustDecodeBounds = false;//加载图像 bmp = BitmapFactory.decodeFile(imageFilePath,opts);//根据指定参数加载图像
iv.setImageBitmap(bmp);//显示图像
posted on 2014-11-03 16:13 recollect088 阅读(191) 评论(0) 收藏 举报
浙公网安备 33010602011771号