android studio 调用相机,并限制像素,请给出代码
时间: 2023-04-02 13:03:01 浏览: 147
以下是调用相机并限制像素的 Android Studio 代码示例:
```
private static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
// 限制像素
int maxWidth = 100;
int maxHeight = 100;
int width = imageBitmap.getWidth();
int height = imageBitmap.getHeight();
float ratio = (float) width / (float) height;
if (width > height) {
width = maxWidth;
height = (int) (width / ratio);
} else {
height = maxHeight;
width = (int) (height * ratio);
}
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, width, height, true);
// 在这里处理图片
}
}
```
以上代码中,我们首先调用相机,然后在 `onActivityResult` 方法中获取拍摄的照片,并对其进行像素限制。我们将图片的最大宽度和高度设置为 100,然后根据图片的宽高比计算出新的宽度和高度。最后,我们使用 `Bitmap.createScaledBitmap` 方法将图片缩放到新的宽度和高度,并在这里处理图片。
阅读全文