Advertisement
FrayxRulez

Capture, scale and crop to get portrait 640x1136 photo

Aug 24th, 2014
451
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.88 KB | None | 0 0
  1.         private async Task<StorageFile> CaptureImage()
  2.         {
  3.             var stream = new InMemoryRandomAccessStream();
  4.             await Viewfinder.CapturePhotoToStreamAsync(stream, ImageEncodingProperties.CreateJpeg());
  5.  
  6.             var decoder = await BitmapDecoder.CreateAsync(stream);
  7.  
  8.             var scale = (double)1136 / (double)decoder.PixelWidth;
  9.  
  10.             var scaledHeight = (uint)(decoder.PixelWidth * 9 / 16);
  11.             var startPointY = (uint)((decoder.PixelHeight - scaledHeight) / 2);
  12.  
  13.             var bounds = new BitmapBounds();
  14.             bounds.X = 0;
  15.             bounds.Y = (uint)Math.Floor((double)(startPointY * scale));
  16.             bounds.Height = 640;
  17.             bounds.Width = 1136;
  18.  
  19.             var photoStorage = await ApplicationData.Current.LocalFolder.CreateFileAsync("image.jpg", CreationCollisionOption.ReplaceExisting);
  20.             var outputStream = await photoStorage.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
  21.  
  22.             outputStream.Size = 0;
  23.  
  24.  
  25.             var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);
  26.             encoder.BitmapTransform.Bounds = bounds;
  27.             encoder.BitmapTransform.ScaledHeight = (uint)Math.Floor((double)(decoder.PixelHeight * scale));
  28.             encoder.BitmapTransform.ScaledWidth = (uint)Math.Floor((double)(decoder.PixelWidth * scale));
  29.  
  30.             var rotation = App.ViewModel.VideoLocation == Windows.Devices.Enumeration.Panel.Back ? PhotoOrientation.Rotate270 : PhotoOrientation.Rotate90;
  31.             var properties = new BitmapPropertySet();
  32.             properties.Add("System.Photo.Orientation", new BitmapTypedValue(rotation, PropertyType.UInt16));
  33.  
  34.             await encoder.BitmapProperties.SetPropertiesAsync(properties);
  35.  
  36.             await encoder.FlushAsync();
  37.  
  38.             outputStream.Dispose();
  39.  
  40.             return photoStorage;
  41.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement