在我的应用程序中,我有一个活动,我们可以使用intent在按钮点击时从相机捕获图像,并将捕获的图像设置为imageview。它的工作非常好。
但现在我想要特定尺寸的图像。例如,在我的情况下,我的图像视图的尺寸是150dp * 150dp。因此我希望相机拍摄的图像尺寸也应始终为150dp * 150dp才能完美贴合。我怎么能这样做?
这是我的主要活动。
public class MainActivity extends Activity implements OnClickListener {
Button btnTackPic;
TextView tvHasCamera, tvHasCameraApp;
ImageView ivThumbnailPhoto;
Bitmap bitMap;
static int TAKE_PICTURE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get reference to views
tvHasCamera = (TextView) findViewById(R.id.tvHasCamera);
tvHasCameraApp = (TextView) findViewById(R.id.tvHasCameraApp);
btnTackPic = (Button) findViewById(R.id.btnTakePic);
ivThumbnailPhoto = (ImageView) findViewById(R.id.ivThumbnailPhoto);
// Does your device have a camera?
if(hasCamera()){
tvHasCamera.setBackgroundColor(0xFF00CC00);
tvHasCamera.setText("You have Camera");
}
// Do you have Camera Apps?
if(hasDefualtCameraApp(MediaStore.ACTION_IMAGE_CAPTURE)){
tvHasCameraApp.setBackgroundColor(0xFF00CC00);
tvHasCameraApp.setText("You have Camera Apps");
}
// add onclick listener to the button
btnTackPic.setOnClickListener(this);
}
// on button "btnTackPic" is clicked
@Override
public void onClick(View view) {
// create intent with ACTION_IMAGE_CAPTURE action
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Edit to save picture
File file = new File(Environment.getExternalStorageDirectory(), "my-photo.jpg");
Uri photoPath = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoPath);
// start camera activity
startActivityForResult(intent, TAKE_PICTURE);
}
// The Android Camera application encodes the photo in the return Intent delivered to onActivityResult()
// as a small Bitmap in the extras, under the key "data"
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == TAKE_PICTURE && resultCode== RESULT_OK && intent != null){
// get bundle
Bundle extras = intent.getExtras();
// get
bitMap = (Bitmap) extras.get("data");
ivThumbnailPhoto.setImageBitmap(bitMap);
}
}
// method to check you have a Camera
private boolean hasCamera(){
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
// method to check you have Camera Apps
private boolean hasDefualtCameraApp(String action){
final PackageManager packageManager = getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
}
提前致谢。
答案 0 :(得分:1)
您需要扩展您的位图,如下面的代码:
Bitmap originalBitmap = <the original bitmap>;
Bitmap resizedBitmap = Bitmap.createScaledBitmap(
originalBitmap, newWidth, newHeight, false);
因此,根据您的要求,调整大小的位图必须生成为:
Bitmap resizedBitmap = Bitmap.createScaledBitmap(
bitMap, 150,150, false);
注意:这里150是以像素为单位测量的,因此您必须计算150dp到像素,然后放置它。