0
我使用這個代碼從庫獲取圖像:爲什麼我無法從相機拍攝圖像,但可以從android中的圖庫中獲取圖像?
fromGalleryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
canvasPictureDialog.dismiss();
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
//startActivity(intent);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),10);
//finish();
}
});
並採取從相機圖像我用這個代碼:
private static final int TAKE_PHOTO_CODE = 1;
private void takePhoto(){
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(this)));
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
private File getTempFile(Context context){
//it will return /sdcard/image.tmp
//final File path = new File(Environment.getExternalStorageDirectory(), context.getPackageName());
final File path = new File(Environment.getExternalStorageDirectory(), context.getPackageName());
if(!path.exists()){
path.mkdir();
}
return new File(path, "image.tmp");
}
而對於onActivityResult常見的代碼是:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10 && resultCode == Activity.RESULT_OK) {
Uri contentUri = data.getData();
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
//Bitmap croppedImage = BitmapFactory.decodeFile(imagePath);
tempBitmap = BitmapFactory.decodeFile(imagePath);
photoBitmap = Bitmap.createScaledBitmap(tempBitmap, display.getWidth(), display.getHeight(), true);
}
if(resultCode == RESULT_OK && requestCode==TAKE_PHOTO_CODE){
final File file = getTempFile(this);
try {
tempBitmap = Media.getBitmap(getContentResolver(), Uri.fromFile(file));
photoBitmap = Bitmap.createScaledBitmap(tempBitmap, display.getWidth(), display.getHeight(), true);
// do whatever you want with the bitmap (Resize, Rename, Add To Gallery, etc)
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
現在使用這個代碼我正在畫布上繪製圖像:
if(!(imagePath==null))
{
//tempBitmap = BitmapFactory.decodeFile(imagePath);
//photoBitmap = Bitmap.createScaledBitmap(tempBitmap, display.getWidth(), display.getHeight(), true);
canvas.drawBitmap (photoBitmap,0, 0, null);
}
但是有了這種用法,我可以從圖庫中獲取圖像,但不能從相機獲取圖像。爲什麼? 我的代碼有什麼問題? 謝謝。
在控制檯中是否有任何錯誤? Android Manifest.xml中有沒有權限'CAMERA'? –
什麼是.tmp ?????????????????????????將其另存爲.jpg或.png或.gif或.bmp並檢查輸出 –
.tmp是相機捕獲的臨時圖像文件。我試着用你的想法,但仍然有這個錯誤..。 –