【问题标题】:How to capture an image?如何捕捉图像?
【发布时间】:2018-07-31 01:50:49
【问题描述】:

我在通过相机在 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);
   }
}

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

【问题讨论】:

  • 你能分享captureImage();方法的代码吗?
  • private void captureImage() { 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); }
  • 请自行更新相关代码。在 cmets 中不推荐
  • 看看这个链接stackoverflow.com/questions/49232265/…它可能对你有帮助

标签: android


【解决方案1】:

检查与来自相机的捕获图像的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 方法中使用 ExifInterface活动。

【讨论】:

  • 感谢您的解决方案。我会试试你的逻辑。 :)
  • 你的源代码在我的手机上试试。这是类似的问题。三星手机依旧风景。它应该是纵向的,因为我的设备是纵向的
  • 尝试根据条件改变rotate变量的值。
【解决方案2】:

试试这个代码:

   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);

        }
    }

【讨论】:

  • 感谢您的解决方案。如果我知道,为什么捕获的图像会转换为 base64?
猜你喜欢
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
  • 2017-06-19
  • 1970-01-01
  • 1970-01-01
  • 2019-04-19
  • 2017-06-18
  • 2015-09-26
相关资源
最近更新 更多