Page 1 of 1

Tutorial: Resizing an image and saving it

Posted: Thu May 23, 2019 3:51 am
by JS-Support @Userware

Here is a tutorial to resize and save an image.

1. Make sure you have the version 2.0 Preview 0.6 of CSHTML5 (expected June 2019) so that you have the "Image.INTERNAL_DomImageElement" property. In the meantime, you can compile the source code from GitHub at: to get this property.

2. Create a CSHTML5 project

3. Copy an image into the project. For example, let's call it "my-source-image.jpg"

4. Put the following XAML in your MainPage.xaml:

Code: Select all

        <Image x:Name="Image1" Source="my-source-image.jpg"/>
        <Button Content="Resize" Click="Button_Click"/>

5. Put the following C# in your MainPage.xaml.cs:

Code: Select all

        private void Button_Click(object sender, RoutedEventArgs e)
            if (Image1.IsLoaded)
                ResizeAndSave(Image1, 100, 100);

        public static void ResizeAndSave(Image imageControl, int finalWidth, int finalHeight)
    // Reference the C# arguments from the JavaScript scope. Refer to the documentation at:
    var sourceImage = $0;
    var finalWidth = $1;
    var finalHeight = $2;

    // Resize the image. Credits:
    var tempCanvas = document.createElement('canvas');
    var tempCanvasContext = tempCanvas.getContext('2d');
    tempCanvas.width = finalWidth;
    tempCanvas.height = finalHeight;
    tempCanvasContext.drawImage(sourceImage, 0, 0, finalWidth, finalHeight);

    // Save the image. Credits:
    var image = tempCanvas.toDataURL('image/png').replace('image/png', 'image/octet-stream');
    window.location.href = image;
    imageControl.INTERNAL_DomImageElement, finalWidth, finalHeight);


6. Launch the Simulator, click the option "Use http://localhost", and click "Run in browser".

  • The image will be downloaded without the extension. You need to change the extension to ".png" (or patch the code above)
  • Downloading the image won't work in the Simulator (please expect a JS error when running the code above)
  • Downloading the image may have security cross-domain issues if you run from C: This is why you need to check the option "Use http://localhost".