Android 如何拍摄图像?

Android 如何拍摄图像?,android,Android,我无法通过摄像头在Android上拍摄图像。我在下面显示了我的Android应用程序的来源 public class RegisterActivity extends AppCompatActivity { private Kelolajson json; private Button btnfoto; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(

我无法通过摄像头在Android上拍摄图像。我在下面显示了我的Android应用程序的来源

public class RegisterActivity extends AppCompatActivity {
   private Kelolajson json;
   private Button btnfoto;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());

      ......
      json = new KelolaJson();
      btnfoto = (Button) findViewById(R.id.fotobtn);
      btnfoto.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            if (isDeviceSupportCamera()) {
               f_foto =txthp.getText().toString() +".jpg";
               fname= txthp.getText().toString();
               captureImage();
            }
            else {
               Toast.makeText(getApplicationContext(),"Your Mobile don't support camera",Toast.LENGTH_LONG).show();
            }
         }
      });
      ......
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
         if (resultCode == RESULT_OK) {
            // successfully captured the image display it in image view
            String root = Environment.getExternalStorageDirectory().toString();
            String path = root + "/Pictures/myapp";
            gmbpath = fileUri.getPath().toString();

            Bitmap tmp = BitmapFactory.decodeFile(gmbpath);
            imgpreview.setImageBitmap(tmp);

         } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(),
                        "You has been canceled capture.",
                        Toast.LENGTH_SHORT).show();
         } else {
            // failed to capture image
            Toast.makeText(getApplicationContext(),
                        "Sorry, Can\'t get photo",
                        Toast.LENGTH_SHORT).show();
          }
       }
   }

   public Uri getOutputMediaFileUri(int type) {
       return Uri.fromFile(getOutputMediaFile(type));
   }

   private static File getOutputMediaFile(int type) {

       //External sdcard location
       File mediaStorageDir = new File(
      Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "myapp");   

       // 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",
                Locale.getDefault()).format(new Date());
       File mediaFile = null;
       if (type == MEDIA_TYPE_IMAGE) {
           fname = "_" + timeStamp;
           f_foto = tmp_hp + ".jpg";
           mediaFile = new File(mediaStorageDir.getPath() + File.separator + f_foto);


       } else {
           mediaFile= null;
       }

       return mediaFile;
   }

   private void captureImage() {
       Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

       fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
       intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
       // start the image capture Intent
       startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
   }
}

此源代码在移动智能手机上运行良好。但一些智能手机拍摄照片的结果总是会改变方向。例如,我通过智能手机纵向拍摄图像,但智能手机拍摄图像的结果是横向。此外,如果是横向方向,则结果将更改为纵向方向。此结果不符合智能手机方向。

检查与相机拍摄图像的
URI
相关的方向

  try {
         getContentResolver().notifyChange(imageUri, null);
         File imageFile = new File(imagePath);
         ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
         int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                                ExifInterface.ORIENTATION_NORMAL);

          switch (orientation) {
          case ExifInterface.ORIENTATION_ROTATE_270:
          rotate = 270;
          break;
          case ExifInterface.ORIENTATION_ROTATE_180:
          rotate = 180;
          break;
          case ExifInterface.ORIENTATION_ROTATE_90:
          rotate = 90;
          break;
        }
          Log.v(Common.TAG, "Exif orientation: " + orientation);
        } catch (Exception e) {
          e.printStackTrace();
        }

         Matrix matrix = new Matrix();
         matrix.postRotate(orientation);
         Bitmap cropped = Bitmap.createBitmap(scaled, x, y, width, height, matrix, true);
显然,三星手机设置了EXIF方向标记,而不是旋转单个像素。使用
BitmapFactory
读取位图不支持此标记。我发现解决此问题的方法是在活动的
onActivityResult
方法中使用
ExiFinInterface

尝试以下代码:

   private static final int CAMERA_PIC_REQUEST = 1337;

    Button btnn;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnn = (Button) findViewById(R.id.btn);
        imageView = (ImageView) findViewById(R.id.Img);
        sf = getSharedPreferences("photo", Context.MODE_PRIVATE);
        String de = sf.getString("image", "");
        byte[] c = Base64.decode(de, Base64.DEFAULT);
        Bitmap bb = BitmapFactory.decodeByteArray(c, 0, c.length);
        imageView.setImageBitmap(bb);


        btnn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, CAMERA_PIC_REQUEST);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK && null != data) {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            byte[] b = bytes.toByteArray();
            String img = Base64.encodeToString(b, Base64.DEFAULT);
            SharedPreferences.Editor editor = sf.edit();
            editor.putString("image", img);
            editor.commit();


            imageView.setImageBitmap(thumbnail);

        }
    }

你能分享
captureImage()的代码吗方法?私有void captureImage(){Intent Intent Intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);fileUri=getOutputMediaFileUri(MEDIA_TYPE_IMAGE);Intent.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);//启动图像捕获Intent startActivityForResult(Intent,CAMERA_CAPTURE_IMAGE_REQUEST_code)}请更新有问题的代码本身。在评论中不建议这样做。请查看此链接,它可能会帮助您感谢您的解决方案。如果我知道,为什么要将捕获的图像转换为base64?感谢您的解决方案。我试试你的逻辑。:)你的源代码可以在我的手机上试用。这是类似的问题。三星手机依然是一片风景。它应该是纵向的,因为我的设备是纵向的,可以根据条件更改旋转变量的值。