Skip to main content

Resizing an image within a Windows 8 app in C#

I'm creating an application where a user can add their own images. Accepting a user's pictures is handy and all but when modern digital cameras regularly take pictures that are greater than 4MB that's not something I want stored in memory.

Here I have image data within a stream and want to resize it to a given width and height - while maintaining aspect ratio. This accomplishes the task nicely...

  1.         /// <summary> 
  2.         /// Resizes image data within a stream to a given width and height.
  3.         /// </summary>
  4.         /// <returns>
  5.         /// Returns an image stream with the resized image data.
  6.         /// </returns>
  7.         public async Task<IRandomAccessStream> ResizeImage(IRandomAccessStream imageStream, uint width, uint height)
  8.         {
  9.             IRandomAccessStream resizedStream = imageStream;
  10.             var decoder = await BitmapDecoder.CreateAsync(imageStream);
  11.             if (decoder.OrientedPixelHeight > height || decoder.OrientedPixelWidth > width)
  12.             {
  13.                 resizedStream = new InMemoryRandomAccessStream();
  14.                 BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);
  15.                 double widthRatio = (double)width / decoder.OrientedPixelWidth;
  16.                 double heightRatio = (double)height / decoder.OrientedPixelHeight;
  17.  
  18.                 // Use whichever ratio had to be sized down the most to make sure the image fits within our constraints.
  19.                 double scaleRatio = Math.Min(widthRatio, heightRatio);
  20.                 uint aspectHeight = (uint)Math.Floor((double)decoder.OrientedPixelHeight * scaleRatio);
  21.                 uint aspectWidth = (uint)Math.Floor((double)decoder.OrientedPixelWidth * scaleRatio);
  22.  
  23.                 encoder.BitmapTransform.ScaledHeight = aspectHeight;
  24.                 encoder.BitmapTransform.ScaledWidth = aspectWidth;
  25.  
  26.                 // write out to the stream
  27.                 await encoder.FlushAsync();
  28.  
  29.                 // Reset the stream location.
  30.                 resizedStream.Seek(0);
  31.             }
  32.  
  33.             return resizedStream;
  34.         }