Tutorial: Resizing an image and saving it

JS-Support @Userware
Site Admin
Posts: 1071
Joined: Tue Apr 08, 2014 3:42 pm

Tutorial: Resizing an image and saving it

Postby JS-Support @Userware » Thu May 23, 2019 3:51 am

Hi,

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: https://github.com/cshtml5/CSHTML5 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

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


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)
        {
            CSHTML5.Interop.ExecuteJavaScript(
@"
    // Reference the C# arguments from the JavaScript scope. Refer to the documentation at: http://cshtml5.com/links/how-to-call-javascript.aspx
    var sourceImage = $0;
    var finalWidth = $1;
    var finalHeight = $2;

    // Resize the image. Credits: https://stackoverflow.com/questions/19262141/resize-image-with-javascript-canvas-smoothly
    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: https://stackoverflow.com/questions/10673122/how-to-save-canvas-as-an-image-with-canvas-todataurl
    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".

Notes:
  • 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".

Regards

Return to “Extensions and Plugins for CSHTML5”

Who is online

Users browsing this forum: No registered users and 0 guests

 

 

cron