Android getting an image from gallery comes rotated

后端 未结 6 1309
闹比i
闹比i 2020-11-30 20:08

I am trying to let users select a profile picture from gallery. My issue is that some pictures come as rotated to the right.

I start the image picker like so:

<
6条回答
  •  醉酒成梦
    2020-11-30 20:40

    I do it this way:

    public void browseClick(View view) {
        view.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.button_animation));
        Intent i = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    
        startActivityForResult(i, RESULT_LOAD_IMAGE);
    }
    

    And the result where the orientation is checked will interest you most:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
    
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
    
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
    
            Bitmap loadedBitmap = BitmapFactory.decodeFile(picturePath);
    
            Matrix matrix = new Matrix();
            Bitmap scaledBitmap;
            if (loadedBitmap.getWidth() >= loadedBitmap.getHeight()){
                matrix.setRectToRect(new RectF(0, 0, loadedBitmap.getWidth(), loadedBitmap.getHeight()), new RectF(0, 0, 400, 300), Matrix.ScaleToFit.CENTER);
                scaledBitmap = Bitmap.createBitmap(loadedBitmap, 0, 0, loadedBitmap.getWidth(), loadedBitmap.getHeight(), matrix, true);
            } else{
                matrix.setRectToRect(new RectF(0, 0, loadedBitmap.getWidth(), loadedBitmap.getHeight()), new RectF(0, 0, 300, 400), Matrix.ScaleToFit.CENTER);
                scaledBitmap = Bitmap.createBitmap(loadedBitmap, 0, 0, loadedBitmap.getWidth(), loadedBitmap.getHeight(), matrix, true);
            }
    
            File file = new File(getExternalCacheDir(), "image.jpg");
            try {
                FileOutputStream out = new FileOutputStream(file);
                scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                out.flush();
                out.close();
            } catch (Exception e) {
                Log.e("Image", "Convert");
            }
    
            imageView.setImageBitmap(scaledBitmap);
        }
    }
    

提交回复
热议问题