用户权限
<uses-permission android:name="android.permission.CAMERA"></uses-permission> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera.autofocus" />
代码示例:
1.开启相机
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File("/sdcard/test.jpg"))); startActivityForResult(intent, 1);
2.获取图片
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { if (resultCode == Activity.RESULT_OK) { Bitmap cameraBitmap = decodeBitmp("/sdcard/test.jpg"); imageView.setImageBitmap(cameraBitmap); // 存成320*240和50*50 如果是垂直方向,需要对cameraBitmap旋转90度 //MediaStore.Images.Media.insertImage(getContentResolver(), cameraBitmap, null, null); } } super.onActivityResult(requestCode, resultCode, data); }
文件转换为bitmap
public static final float DISPLAY_WIDTH = 200; public static final float DISPLAY_HEIGHT = 200; /** * 从path中获取图片信息 * @param path * @return */ private Bitmap decodeBitmap(String path){ BitmapFactory.Options op = new BitmapFactory.Options(); //inJustDecodeBounds //If set to true, the decoder will return null (no bitmap), but the out… op.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory.decodeFile(path, op); //获取尺寸信息 //获取比例大小 int wRatio = (int)Math.ceil(op.outWidth/DISPLAY_WIDTH); int hRatio = (int)Math.ceil(op.outHeight/DISPLAY_HEIGHT); //如果超出指定大小,则缩小相应的比例 if(wRatio > 1 && hRatio > 1){ if(wRatio > hRatio){ op.inSampleSize = wRatio; }else{ op.inSampleSize = hRatio; } } op.inJustDecodeBounds = false; bmp = BitmapFactory.decodeFile(path, op); return bmp; }
时间: 2024-10-13 01:28:43