How to resize Image in C# WinRT/winmd?

Example of how to scale and crop taken from here:

async private void BitmapTransformTest()
{
    // hard coded image location
    string filePath = "C:\\Users\\Public\\Pictures\\Sample Pictures\\fantasy-dragons-wallpaper.jpg";

    StorageFile file = await StorageFile.GetFileFromPathAsync(filePath);
    if (file == null)
        return;

    // create a stream from the file and decode the image
    var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);


    // create a new stream and encoder for the new image
    InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
    BitmapEncoder enc = await BitmapEncoder.CreateForTranscodingAsync(ras, decoder);

    // convert the entire bitmap to a 100px by 100px bitmap
    enc.BitmapTransform.ScaledHeight = 100;
    enc.BitmapTransform.ScaledWidth = 100;


    BitmapBounds bounds = new BitmapBounds();
    bounds.Height = 50;
    bounds.Width = 50;
    bounds.X = 50;
    bounds.Y = 50;
    enc.BitmapTransform.Bounds = bounds;

    // write out to the stream
    try
    {
        await enc.FlushAsync();
    }
    catch (Exception ex)
    {
        string s = ex.ToString();
    }

    // render the stream to the screen
    BitmapImage bImg = new BitmapImage();
    bImg.SetSource(ras);
    img.Source = bImg; // image element in xaml

}

Leave a Comment