2015-09-14 2 views
2

Я пишу приложение андроида форм Xamarin, где я беру изображения из галереи. Я хочу загрузить эти изображения на сервер, поэтому мне нужно байт []. Я масштабирую и сжимаю эти изображения, а затем беру байт []. Моя проблема в том, что когда я сжимаю изображение, изображение меняет ориентацию от портрета к пейзажу. Я попытался использовать класс «ExifInterface» и изменил ориентацию изображения, но он не работает. Ниже приведен мой полный код: -Xamarin Forms Android Изменения ориентации изображения после сжатия

protected override async void OnActivityResult (int requestCode, Result resultCode, Intent data) 
    { 
     if (resultCode == Result.Canceled) 
      return; 

     try { 
      var mediafile = await data.GetMediaFileExtraAsync (Forms.Context); 

      byte[] data1 = ReadFully (mediafile.GetStream()); 

      byte[] resizedImage = ResizeImageAndroid (data1, 60, 60, mediafile); 
      var imageStream = new ByteArrayContent (resizedImage); 
      imageStream.Headers.ContentDisposition = new ContentDispositionHeaderValue ("attachment") { 
       FileName = Guid.NewGuid() + ".Png" 
      }; 

      var multi = new MultipartContent(); 
      multi.Add (imageStream); 
      HealthcareProfessionalDataClass lDataClass = HealthcareProfessionalDataClass.Instance; 
      lDataClass.Thumbnail = multi; 
      App.mByteArrayOfImage = data1; 

      System.Diagnostics.Debug.WriteLine (mediafile.Path); 

      MessagingCenter.Send<IPictureTaker,string> (this, "picturetaken", mediafile.Path); 
     } catch (Java.Lang.Exception e) { 
      e.PrintStackTrace(); 
     } 
    } 

public static byte[] ReadFully (System.IO.Stream input) 
    { 
     using (var ms = new MemoryStream()) { 
      input.CopyTo (ms); 
      return ms.ToArray(); 
     } 
    } 

public static byte[] ResizeImageAndroid (byte[] imageData, float width, float height, MediaFile file) 
    { 
     try { 
      // Load the bitmap 

      var options = new BitmapFactory.Options(); 
      options.InJustDecodeBounds = true; 

      // Calculate inSampleSize 
      options.InSampleSize = calculateInSampleSize (options, (int)width, (int)height); 
      // Decode bitmap with inSampleSize set 
      options.InJustDecodeBounds = false; 

      Bitmap originalImage = BitmapFactory.DecodeByteArray (imageData, 0, imageData.Length, options); 
      Bitmap resizedImage = Bitmap.CreateScaledBitmap (originalImage, (int)width, (int)height, false); 


      using (var ms = new MemoryStream()) { 

       resizedImage.Compress (Bitmap.CompressFormat.Png, 0, ms); 
       resizedImage = changeOrientation (file, resizedImage); 

       return ms.ToArray(); 
      } 
     } catch (Java.Lang.Exception e) { 
      e.PrintStackTrace(); 
      return null; 
     } 
    } 

public static int calculateInSampleSize (BitmapFactory.Options options, int reqWidth, int reqHeight) 
    { 
     // Raw height and width of image 
     int height = options.OutHeight; 
     int width = options.OutWidth; 
     int inSampleSize = 4; 

     if (height > reqHeight || width > reqWidth) { 

      int halfHeight = height/2; 
      int halfWidth = width/2; 

      // Calculate the largest inSampleSize value that is a power of 2 and keeps both 
      // height and width larger than the requested height and width. 
      while ((halfHeight/inSampleSize) > reqHeight 
        && (halfWidth/inSampleSize) > reqWidth) { 
       inSampleSize *= 2; 
      } 
     } 

     return inSampleSize; 
    } 

static Bitmap changeOrientation (MediaFile mediafile, Bitmap bitmap) 
    { 
     var exifInterface = new ExifInterface (mediafile.Path); 
     int orientation = exifInterface.GetAttributeInt (ExifInterface.TagOrientation, 0); 
     var matrix = new Matrix(); 
     switch (orientation) { 
     case 2: 
      matrix.SetScale (-1, 1); 
      break; 
     case 3: 
      matrix.SetRotate (180); 
      break; 
     case 4: 
      matrix.SetRotate (180); 
      matrix.PostScale (-1, 1); 
      break; 
     case 5: 
      matrix.SetRotate (90); 
      matrix.PostScale (-1, 1); 
      break; 
     case 6: 
      matrix.SetRotate (90); 
      break; 
     case 7: 
      matrix.SetRotate (-90); 
      matrix.PostScale (-1, 1); 
      break; 
     case 8: 
      matrix.SetRotate (-90); 
      break; 
     default: 
      return bitmap; 
     } 

     try { 
      Bitmap oriented = Bitmap.CreateBitmap (bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, true); 
      bitmap.Recycle(); 
      return oriented; 
     } catch (OutOfMemoryError e) { 
      e.PrintStackTrace(); 
      return bitmap; 
     } catch (System.Exception e) { 
      System.Diagnostics.Debug.WriteLine (e.Message); 
      return bitmap; 
     } 
    } 

Если у кого-то есть решение моей проблемы, пожалуйста, дайте мне знать.

ответ

1

Я не уверен, что я пропустил его, но он чувствует, что матрица не назначена ни одному изображению? Поэтому любое изменение, которое вы делаете в матрице, вы никогда не увидите.

Так я пошел вокруг реализации этого было:

Matrix mtx = new Matrix(); 
    ExifInterface exif = new ExifInterface(fileName); 
    string orientation = exif.GetAttribute(ExifInterface.TagOrientation); 

    switch (orientation) 
    { 
     case "6": // portrait 
      mtx.PreRotate(90); 
      resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false); 
      mtx.Dispose(); 
      mtx = null; 
      break; 
     case "1": // landscape 
      break; 
     case "8": // Selfie ORIENTATION_ROTATE_270 - might need to flip horizontally too... 
      mtx.PreRotate(270); 
      resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false); 
      mtx.Dispose(); 
      mtx = null; 
      break; 
    } 

Это матрица .preRotate присваивается Bitmap.CreateBitmap(), то вернуть это изменение размера растрового изображения. Надеюсь, это поможет :)

+0

Спасибо за ваш ответ. Я уже пробовал это, но он не работает. Также я заметил, что моя проблема связана только с изображениями, снятыми с камеры. Когда я устал от других изображений, он работает нормально. – Amrut

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