2017-02-15 4 views
1

У меня есть способ сделать снимок, взять образец вертикальной формы так же, как я хочу, горизонтальный круг и сохранить вертикальную фотографию так же, как я желаю для упражнений упражнения, активность называется ViewerActivity, и это здесь. Когда проблема начинается с момента отображения в ImageView фотографии горизонтальной выборки:/он читает, и есть класс ExifInterface, который позволяет управлять ориентацией изображения, но в момент отображения изображения все еще горизонтальноonActivityResult с ImageView

Этот класс является ответственным за отправку фотографии.

public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) { 
     try { 
      ExifInterface exifInterface = new ExifInterface(photoFile.getAbsolutePath()); 
      int valor = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); 
      switch (valor) { 
       case ExifInterface.ORIENTATION_ROTATE_90: 
        orientation = 90; 
        break; 
       case ExifInterface.ORIENTATION_ROTATE_180: 
        orientation = 180; 
        break; 
       case ExifInterface.ORIENTATION_ROTATE_270: 
        orientation = 270; 
        break; 
      } 
     } catch (Exception e) { 
      Log.d("mensaje", e.toString()); 
     } 
     Intent i = new Intent(this, ViewerActivity.class); 
     i.putExtra(EXTRA_PHOTO_PATH, photoFile.getAbsolutePath()); 
     i.putExtra(EXTRA_PHOTO_ORIENTATION, orientation); 
     i.putExtra(EXTRA_PHOTO_EDIT, false); 
     startActivityForResult(i, 10); 

Этот класс ViewerActivity отображает фотографию, а затем отправляет его

private void sendPicture() { 
    Intent intent = new Intent(); 
    intent.putExtra("path", localPath); 
    intent.putExtra("orientation",orientation); 
    setResult(Activity.RESULT_OK, intent); 
    finish(); 
} 

ответ

0

Попробуйте это:

BitmapFactory.Options bounds = new BitmapFactory.Options(); 
bounds.inJustDecodeBounds = true; 
BitmapFactory.decodeFile(file, bounds); 

BitmapFactory.Options opts = new BitmapFactory.Options(); 
Bitmap bm = BitmapFactory.decodeFile(file, opts); 
ExifInterface exif = new ExifInterface(file); 
String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION); 
int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL; 

int rotationAngle = 0; 
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90; 
if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180; 
if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270; 

Matrix matrix = new Matrix(); 
matrix.setRotate(rotationAngle, (float) bm.getWidth()/2, (float) bm.getHeight()/2); 
Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bounds.outWidth, bounds.outHeight, matrix, true);` 

где file это имя файла изображения.

+0

Здравствуйте, но возникают другое мое сомнение относительно этого метода, может быть реализована в часть, когда я снимаю фотографию, или когда я уже отправляю ее на изображение? Спасибо за поддержку. – Devix

+0

Преобразуйте растровое изображение результата в файл и сделайте это. –

0
try { 
File f = new File(imagePath); 
ExifInterface exif = new ExifInterface(f.getPath()); 
int orientation = exif.getAttributeInt(
     ExifInterface.TAG_ORIENTATION, 
     ExifInterface.ORIENTATION_NORMAL); 

int angle = 0; 

if (orientation == ExifInterface.ORIENTATION_ROTATE_90) { 
    angle = 90; 
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) { 
    angle = 180; 
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) { 
    angle = 270; 
} 

Matrix mat = new Matrix(); 
mat.postRotate(angle); 
BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inSampleSize = 2; 

Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(f), 
     null, options); 
bitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), 
     bmp.getHeight(), mat, true); 
ByteArrayOutputStream outstudentstreamOutputStream = new ByteArrayOutputStream(); 
bitmap.compress(Bitmap.CompressFormat.PNG, 100, 
     outstudentstreamOutputStream); 
imageView.setImageBitmap(bitmap); 

} catch (IOException e) { 
Log.w("TAG", "-- Error in setting image"); 
} catch (OutOfMemoryError oom) { 
Log.w("TAG", "-- OOM Error in setting image"); 
} 

попробовать это, когда вы получаете ImagePath в onActivityResult

+0

Привет, друг, в настоящий момент я реализую этот метод, чтобы посмотреть, как это получится, и я скажу вам спасибо – Devix

1

Используйте RotateLayout, полный класс и образец доступен в ссылке ниже.

https://github.com/rongi/rotate-layout

использование RotateLayout довольно легко и меньше потребление памяти сравнить, чтобы сделать новый повернутый Bitmap с помощью Matrix.

место вашего ImageView внутри RotateLayout, как показано ниже Кодекса

<com.github.rongi.rotate_layout.layout.RotateLayout 
    android:id="@+id/form3_container" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    app:angle="180"> 

    <ImageView 
    android:id="@+id/imageview" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    /> 
</com.github.rongi.rotate_layout.layout.RotateLayout> 

и установить orientation значения, которое получает путь ExifInterface в angle собственности в RotateLayout й ImageView поворачиваются и вам не нужно беспокоиться за растровый или любую другую вещь для ExifInterfaceorientation.

Вы можете установить значение угла динамически из кода Java, в RotateLayout объект как ниже

rotateLayout.setAngle(newAngle); 
+0

Привет друг может также добавить таргетинг на изображение нет? И будет ли он работать одинаково? whit this method imageView.setRotation (90); – Devix

+0

@JoseAnguiano yes imageView.setRotation (90) работает, но когда, растровое изображение Ориентация Exif - это пейзаж, а когда мы поворачиваем на 90, тогда соотношение сторон растрового изображения в изображении не поддерживается –

0

Попробуйте

public Bitmap rotateImage() { 
    Bitmap scaled = null; 
    try { 
     FileInputStream fis = new FileInputStream(file); 
     BitmapFactory.Options bounds = new BitmapFactory.Options(); 
     bounds.inJustDecodeBounds = true; 
     Bitmap bm = BitmapFactory.decodeStream(fis); 

     ExifInterface exif = new ExifInterface(file.getAbsolutePath()); 

     String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION); 
     int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL; 
     int rotationAngle = 0; 
     if (orientation == ExifInterface.ORIENTATION_ROTATE_90) 
      rotationAngle = 90; 
     if (orientation == ExifInterface.ORIENTATION_ROTATE_180) 
      rotationAngle = 180; 
     if (orientation == ExifInterface.ORIENTATION_ROTATE_270) 
      rotationAngle = 270; 
     Matrix matrix = new Matrix(); 
     matrix.setRotate(rotationAngle, (float) bm.getWidth()/2, (float) bm.getHeight()/2); 
     Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true); 
     int height = rotatedBitmap.getHeight(), scaledheight, scaledwidth; 
     int width = rotatedBitmap.getWidth(); 
     float aspect; 

     if (width < height) {// portrait 
      aspect = ((float) height/(float) width); 
      scaledwidth = 400; 
      scaledheight = (int) (400 * aspect); 
     } else {// landscape 
      aspect = ((float) width/(float) height); 
      scaledheight = 400; 
      scaledwidth = (int) (400 * aspect); 
     } 
     scaled = Bitmap.createScaledBitmap(rotatedBitmap, scaledwidth, scaledheight, false); 

     File f = new File(getCacheDir(), "scaledBitmap"); 
     f.createNewFile(); 

     Bitmap bitmap = scaled; 
     ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     bitmap.compress(Bitmap.CompressFormat.PNG, 0 /* ignored for PNG */, bos); 
     byte[] bitmapdata = bos.toByteArray(); 

     FileOutputStream fos = new FileOutputStream(f); 
     fos.write(bitmapdata); 
     fos.flush(); 
     fos.close(); 

     file = f; 

    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     Log.e("photofile io error", "EXif not done"); 
    } 
    return scaled; 
} 
Смежные вопросы