我开发了一个应用程序,用户可以从相机或图库中捕获图像。为此,用户可以单击图像视图,然后会出现一个对话框,用户可以选择从相机或图库中捕获。
如果用户选择从图库或前置摄像头捕获图像,则其工作正常,捕获的图像显示在图像视图中。但是,如果用户选择后置摄像头并拍摄照片并返回活动,则图像根本不会显示在图像视图中。
这是我的完整源代码:
public class PostActivity extends Activity implements OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.post);
image = (ImageView) findViewById(R.id.image);
ab = getActionBar();
ab.setDisplayHomeAsUpEnabled(true);
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
show(); //here the dialog box is called, to choose the capture option
}
});
image.setTag(null);
captureImageInitialization();
}
private void show() {
dialog.show();
}
private void captureImageInitialization() {
final Item[] items = {
new Item("Camera", R.drawable.ic_action_camera_dark),
new Item("Gallery", R.drawable.ic_action_collection),
};
ListAdapter adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1, items) {
public View getView(int position, View convertView, ViewGroup parent) {
// User super class to create the View
View v = super.getView(position, convertView, parent);
TextView tv = (TextView) v.findViewById(android.R.id.text1);
// Put the image on the TextView
tv.setCompoundDrawablesWithIntrinsicBounds(
items[position].icon, 0, 0, 0);
// Add margin between image and text (support various screen
// densities)
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
tv.setCompoundDrawablePadding(dp5);
return v;
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Take Image from ...");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(
"android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, PICK_FROM_CAMERA);
} else {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_FROM_FILE);
}
}
});
dialog = builder.create();
}
public static class Item {
public final String text;
public final int icon;
public Item(String text, Integer icon) {
this.text = text;
this.icon = icon;
}
@Override
public String toString() {
return text;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_FROM_CAMERA:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
BitmapFactory.Options options0 = new BitmapFactory.Options();
options0.inSampleSize = 2;
options0.inScaled = false;
options0.inDither = false;
options0.inPreferredConfig = Bitmap.Config.ARGB_8888;
bmp = BitmapFactory.decodeFile(imagepath, options0);
Matrix matrix = new Matrix();
ExifInterface exif;
int m = 0;
try {
exif = new ExifInterface(imagepath);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 1);
Log.d("EXIF", "Exif: " + orientation);
if (orientation == 6) {
m = 90;
} else if (orientation == 3) {
m = 180;
} else if (orientation == 8) {
m = 270;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
matrix.postRotate(m);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
bmp.getHeight(), matrix, false);
ByteArrayOutputStream baos0 = new ByteArrayOutputStream();
image.setImageBitmap(getRoundedCornerBitmap(bmp));
image.setTag("1");
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos0);
byte[] imageBytes0 = baos0.toByteArray();
krt1 = Base64.encodeToString(imageBytes0, Base64.DEFAULT);
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
options.inScaled = false;
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bmp = BitmapFactory.decodeFile(imagepath, options);
ExifInterface exif2;
int m2 = 0;
try {
exif2 = new ExifInterface(imagepath);
int orientation = exif2.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 1);
Log.d("EXIF", "Exif: " + orientation);
if (orientation == 6) {
m2 = 90;
} else if (orientation == 3) {
m2 = 180;
} else if (orientation == 8) {
m2 = 270;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
Matrix matrix2 = new Matrix();
matrix2.postRotate(m2);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
bmp.getHeight(), matrix2, false);
image.setImageBitmap(getRoundedCornerBitmap(bmp));
image.setTag("1");
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos2);
byte[] imageBytes2 = baos2.toByteArray();
krt1 = Base64.encodeToString(imageBytes2, Base64.DEFAULT);
break;
}
}
public String getPath(Uri uri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getApplicationContext().getContentResolver().query(uri,
proj, null, null, null);
if (cursor.moveToFirst()) {
;
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
后置摄像头这个问题真的很奇怪,因为我从未遇到过这样的问题。 (BTW在三星设备上测试过)。任何帮助表示赞赏。
答案 0 :(得分:0)
我正在使用此代码从前置摄像头拍摄图像 -
public class CameraController {
private Context context;
private boolean hasCamera;
private Camera camera;
private int cameraId;
public CameraController(Context c){
context = c.getApplicationContext();
if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
cameraId = getFrontCameraId();
if(cameraId != -1){
hasCamera = true;
}else{
hasCamera = false;
}
}else{
hasCamera = false;
}
}
public boolean hasCamera(){
return hasCamera;
}
public void getCameraInstance(){
camera = null;
if(hasCamera){
try{
camera = Camera.open(cameraId);
prepareCamera();
}
catch(Exception e){
hasCamera = false;
}
}
}
public void takePicture(){
if(hasCamera){
camera.takePicture(null,null,mPicture);
}
}
public void releaseCamera(){
if(camera != null){
camera.stopPreview();
camera.release();
camera = null;
}
}
private int getFrontCameraId(){
int camId = -1;
int numberOfCameras = Camera.getNumberOfCameras();
CameraInfo ci = new CameraInfo();
for(int i = 0;i < numberOfCameras;i++){
Camera.getCameraInfo(i,ci);
if(ci.facing == CameraInfo.CAMERA_FACING_FRONT){
camId = i;
}
}
return camId;
}
private void prepareCamera(){
SurfaceView view = new SurfaceView(context);
try{
camera.setPreviewDisplay(view.getHolder());
}catch(IOException e){
throw new RuntimeException(e);
}
camera.startPreview();
Camera.Parameters params = camera.getParameters();
params.setJpegQuality(100);
camera.setParameters(params);
}
private PictureCallback mPicture = new PictureCallback(){
@Override
public void onPictureTaken(byte[] data, Camera camera){
File pictureFile = getOutputMediaFile();
if(pictureFile == null){
Log.d("TEST", "Error creating media file, check storage permissions");
return;
}
try{
Log.d("TEST","File created");
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
}catch(FileNotFoundException e){
Log.d("TEST","File not found: "+e.getMessage());
} catch (IOException e){
Log.d("TEST","Error accessing file: "+e.getMessage());
}
}
};
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if(!mediaStorageDir.exists()){
if(!mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath()+File.separator+"IMG_"+timeStamp+".jpg");
return mediaFile;
}
}
希望这会对你有所帮助。