Skip to content

Instantly share code, notes, and snippets.

@JerryNixon
Created September 26, 2018 04:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JerryNixon/e58786f1933c14a83f8a404be279bacc to your computer and use it in GitHub Desktop.
Save JerryNixon/e58786f1933c14a83f8a404be279bacc to your computer and use it in GitHub Desktop.
static async Task<string> ScaleImageAsync(string path, uint height = 32, uint width = 32, StorageFile output_file = null)
{
// open file from path
var input_file = default(StorageFile);
try
{
input_file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(path));
}
catch (FileNotFoundException)
{
return null;
}
catch
{
throw;
}
// read file into writeable bitmap
var input_pixels = default(IBuffer);
using (var input_stream = await input_file.OpenReadAsync())
{
var input_decoder = await BitmapDecoder.CreateAsync(input_stream);
var input_bitmap = new WriteableBitmap((int)input_decoder.PixelWidth, (int)input_decoder.PixelHeight);
await input_bitmap.SetSourceAsync(input_stream);
input_pixels = input_bitmap.PixelBuffer;
}
// resize writeable bitmap
var memory_pixels = default(IBuffer);
using (var memory_stream = new InMemoryRandomAccessStream())
{
var memory_encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, memory_stream);
memory_encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, width, height, 96, 96, input_pixels.ToArray());
await memory_encoder.FlushAsync();
memory_stream.Seek(0);
var memory_bitmap = new WriteableBitmap((int)width, (int)height);
await memory_bitmap.SetSourceAsync(memory_stream);
memory_pixels = memory_bitmap.PixelBuffer;
}
// save writeable bitmap to file
var output_folder = ApplicationData.Current.LocalFolder;
output_file = output_file ?? await output_folder.CreateFileAsync($"{Guid.NewGuid()}.jpg");
using (var output_stream = await output_file.OpenAsync(FileAccessMode.ReadWrite))
{
var output_encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, output_stream);
var output_pixels = new byte[memory_pixels.Length];
await memory_pixels.AsStream().ReadAsync(output_pixels, 0, output_pixels.Length);
output_encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, width, height, 96, 96, output_pixels);
await output_encoder.FlushAsync();
}
// return path
return output_file.Path;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment