2016-03-12 3 views
1

То, что яНеправильная ориентация Пользовательские камеры отснятое изображение андроида

Я с CustomCamera, которая захватывает изображения в обоих LANDSCAPE & PORTRATI

Моя проблема

Когда я захватить изображение, он получает сохранено в неправильном направлении (не соответствует ориентации камеры)

Что я хочу Я хотел, чтобы камера сохранила фотографию в правильной ориентации. Я должен обнаружить динамическую ориентацию экрана (но мой CameraActivity ограничивается ПОРТРЕТ :()

То, что я попытался

public Bitmap flip(Bitmap src, int type) { 
     Matrix matrix = new Matrix(); 

     if(type == 0) { // portrait 
      matrix.preScale(1.0f, -1.0f); 
     } 
     else if(type == 1) { // landscape 
      matrix.preScale(-1.0f, 1.0f); 
     } else { 
      return src; 
     } 
     return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true); 
    } 

Я пытается использовать это, установив жесткий код значения но

Это дает мне ЗЕРКАЛА изображение

ответ

0

- Полный код для захвата изображения, сохранения на SD-карте, выбора из галереи, сжатия, поворота изображения и т. Д. 200% работы.

public class A extends AppCompatActivity implements View.OnClickListener, AsyncTaskCompleteListener { 

    private static final String IMAGE_DIRECTORY = "/idyme"; 
    private static int MAX_IMAGE_DIMENSION = 200; 
    private final String TAG = "RegisterFragment"; 
    private Button btnVerify, btnUploadImage; 

    private String ImgPath = null, filePath = null, 
      profileImageFilePath, profileImageData = null,imageVideoType = "", imageVideoPath = ""; 
    private ImageView ivImage; 
    private AQuery aQuery; 
    private Uri uri = null; 
    private ImageOptions imageOptions; 
    ActionBar actionBar; 



    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_vip_registration); 


     ivImage = (ImageView) findViewById(R.id.ivProfile); 
     aQuery = new AQuery(this); 
     imageOptions = new ImageOptions(); 
     imageOptions.memCache = true; 
     imageOptions.fileCache = true; 
     imageOptions.fallback = R.drawable.userimage; 






    } 

    @Override 
    public void onClick(View v) { 
     // onRegisterButtonClick(); 

     switch (v.getId()) { 

      case R.id.btnUploadImage: 
       showPictureDialog(); 
     } 
    } 

    private void showPictureDialog() { 
     AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this); 
     pictureDialog.setTitle(getResources().getString(
       R.string.dialog_chhose_photo)); 
     String[] pictureDialogItems = { 
       getResources().getString(R.string.dialog_from_gallery), 
       getResources().getString(R.string.dialog_from_camera)}; 

     pictureDialog.setItems(pictureDialogItems, 
       new DialogInterface.OnClickListener() { 

        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         switch (which) { 

          case 0: 
           choosePhotoFromGallary(); 
           break; 

          case 1: 
           takePhotoFromCamera(); 
           break; 

         } 
        } 
       }); 
     pictureDialog.show(); 
    } 

    private void choosePhotoFromGallary() { 
     Intent galleryIntent = new Intent(Intent.ACTION_PICK, 
       android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 

     startActivityForResult(galleryIntent, Constants.CHOOSE_PHOTO); 


    } 

    private void takePhotoFromCamera() { 
     Calendar cal = Calendar.getInstance(); 
     File file = new File(Environment.getExternalStorageDirectory(), 
       (cal.getTimeInMillis() + ".jpg")); 

     if (!file.exists()) { 
      try { 
       file.createNewFile(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } else { 

      file.delete(); 
      try { 
       file.createNewFile(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     // uri = Uri.fromFile(file); 
     uri = getOutputMediaFileUri(); 
     Intent cameraIntent = new Intent(
       android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
     cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri); 
     startActivityForResult(cameraIntent, Constants.TAKE_PHOTO); 


    } 

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

    private String getRealPathFromURI(Uri contentURI) { 
     String result; 

     String[] proj = {MediaStore.Images.Media.DATA}; 
     Cursor cursor = this.getContentResolver().query(contentURI, proj, null, null, null); 

     if (cursor == null) { // Source is Dropbox or other similar local file 
      // path 
      result = contentURI.getPath(); 
     } else { 
      cursor.moveToFirst(); 
      int idx = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
      result = cursor.getString(idx); 
      cursor.close(); 
     } 


     return result; 


    } 


    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 

     super.onActivityResult(requestCode, resultCode, data); 
     if (resultCode == this.RESULT_CANCELED) { 
      return; 
     } 
     if (requestCode == Constants.CHOOSE_PHOTO) { 
      if (data != null) { 
       Uri contentURI = data.getData(); 
       profileImageData = getRealPathFromURI(contentURI); 
       // new AQuery(getApplicationContext()).id(ivMeme).image(
       // profileImageData, imageOptions); 
       try { 
        String path = saveImage(scaleImage(this, contentURI)); 
        imageVideoPath = path; 
        aQuery.id(R.id.ivProfile).image(
          imageVideoPath, imageOptions); 
       } catch (IOException e) { 
        e.printStackTrace(); 
        Utils.showToast("Failed", this); 
       } 

      } 

     } else if (requestCode == Constants.TAKE_PHOTO) { 


      // old 
      if (uri != null) { 
       profileImageFilePath = uri.getPath(); 
       if (profileImageFilePath != null 
         && profileImageFilePath.length() > 0) { 
        File myFile = new File(profileImageFilePath); 
        String path = saveImage(BitmapFactory 
          .decodeFile(profileImageFilePath)); 
        imageVideoPath = path; 
        aQuery.id(R.id.ivProfile).image(
          imageVideoPath, imageOptions); 
       } else { 
        Utils.showToast("Failed", this); 
       } 

      } else { 
       Utils.showToast("Failed", this); 
      } 

     } 

    } 

    public String saveImage(Bitmap myBitmap) { 
     ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
     myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes); 
     File wallpaperDirectory = new File(
       Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY); 
     // have the object build the directory structure, if needed. 
     if (!wallpaperDirectory.exists()) { 
      wallpaperDirectory.mkdirs(); 
     } 

     try { 
      File f = new File(wallpaperDirectory, Calendar.getInstance() 
        .getTimeInMillis() + ".jpg"); 
      f.createNewFile(); 
      FileOutputStream fo = new FileOutputStream(f); 
      fo.write(bytes.toByteArray()); 
      MediaScannerConnection.scanFile(this, 
        new String[]{f.getPath()}, 
        new String[]{"image/jpeg"}, null); 
      fo.close(); 
      AppLog.Log("TAG", "File Saved::-> " + f.getAbsolutePath()); 
      return f.getAbsolutePath(); 
     } catch (IOException e1) { 
      e1.printStackTrace(); 
     } 
     return ""; 
    } 


private static File getOutputMediaFile() { 

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

     // Create the storage directory if it does not exist 
     if (!mediaStorageDir.exists()) { 
      if (!mediaStorageDir.mkdirs()) { 
       Log.d(IMAGE_DIRECTORY, "Oops! Failed create " + IMAGE_DIRECTORY 
         + " directory"); 
       return null; 
      } 
     } 

     // Create a media file name 
     String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", 
       Locale.getDefault()).format(new Date()); 
     File mediaFile; 
     mediaFile = new File(mediaStorageDir.getPath() + File.separator 
       + "VID_" + timeStamp + ".mp4"); 

     return mediaFile; 
    } 

    public static Bitmap scaleImage(Context context, Uri photoUri) 
      throws IOException { 
     InputStream is = context.getContentResolver().openInputStream(photoUri); 
     BitmapFactory.Options dbo = new BitmapFactory.Options(); 
     dbo.inJustDecodeBounds = true; 
     BitmapFactory.decodeStream(is, null, dbo); 
     is.close(); 

     int rotatedWidth, rotatedHeight; 
     int orientation = getOrientation(context, photoUri); 

     if (orientation == 90 || orientation == 270) { 
      rotatedWidth = dbo.outHeight; 
      rotatedHeight = dbo.outWidth; 
     } else { 
      rotatedWidth = dbo.outWidth; 
      rotatedHeight = dbo.outHeight; 
     } 

     Bitmap srcBitmap; 
     is = context.getContentResolver().openInputStream(photoUri); 
     if (rotatedWidth > MAX_IMAGE_DIMENSION 
       || rotatedHeight > MAX_IMAGE_DIMENSION) { 
      float widthRatio = ((float) rotatedWidth) 
        /((float) MAX_IMAGE_DIMENSION); 
      float heightRatio = ((float) rotatedHeight) 
        /((float) MAX_IMAGE_DIMENSION); 
      float maxRatio = Math.max(widthRatio, heightRatio); 

      // Create the bitmap from file 
      BitmapFactory.Options options = new BitmapFactory.Options(); 
      options.inSampleSize = (int) maxRatio; 
      srcBitmap = BitmapFactory.decodeStream(is, null, options); 
     } else { 
      srcBitmap = BitmapFactory.decodeStream(is); 
     } 
     is.close(); 

     /* 
     * if the orientation is not 0 (or -1, which means we don't know), we 
     * have to do a rotation. 
     */ 
     if (orientation > 0) { 
      Matrix matrix = new Matrix(); 
      matrix.postRotate(orientation); 

      srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, 
        srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true); 
     } 

     String type = context.getContentResolver().getType(photoUri); 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     if (type.equals("image/png")) { 
      srcBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); 
     } else if (type.equals("image/jpg") || type.equals("image/jpeg")) { 
      srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
     } 
     byte[] bMapArray = baos.toByteArray(); 
     baos.close(); 
     return BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length); 
    } 


    public static int getOrientation(Context context, Uri photoUri) { 
     /* it's on the external media. */ 
     Cursor cursor = context.getContentResolver().query(photoUri, 
       new String[]{MediaStore.Images.ImageColumns.ORIENTATION}, 
       null, null, null); 

     if (cursor.getCount() != 1) { 
      return -1; 
     } 

     cursor.moveToFirst(); 
     return cursor.getInt(0); 
    } 

} 

- Разрешение требуется:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.CAMERA" /> 
+0

становится пустой указатель для курсора в GetOrientation (контекст Context, Uri photoUri). –

Смежные вопросы