How to make an ASP.NET HTML code writer with image resize capabilities

graphical user interface, application, icon

Image resolution is something that we sometimes overlook as developers. Basic functionality, error handling, and intuitiveness come first, after all. However, that doesnโ€™t mean that handling image resolution or size isnโ€™t important. In fact, improper image handling can slow down websites and applications, consume excessive bandwidth, or ruin the UI or UX. One good way to prevent this is by resizing uploaded images before theyโ€™re stored. So, letโ€™s discover how we can build an HTML code writer with image resizing using ASP.NET, ImageMagick, and a WYSIWYG HTML editor.

Key Takeaways

  • Image resizing boosts performance by reducing load times and bandwidth usage.
  • ASP.NET, Froala, and ImageMagick are combined to build a web app with image resizing.
  • Froala Editor allows easy image uploads and rich text editing.
  • ImageMagick simplifies resizing, ensuring images fit set dimensions.
  • Customizable solution with options for validation, enhancement, and more.

Hereโ€™s a little demonstration of our HTML code writerโ€™s image resize capability:

Notice how the 2 sample images had a landscape orientation before being uploaded and how they both changed afterwards. Now, read more to use an ASP.NET-based HTML code writer with image resizing capabilities. For more details, feel free to check our .NET image resize documentation. Now letโ€™s set up the application.

Setting up the application

Before we get to the development part, letโ€™s check out the tools that weโ€™ll be using:

  • ASP.NET Core: An open-source web application framework that comes with Visual Studio
  • ImageMagick: An extensive open-source software suite for enhancing images
  • Froala: A powerful WYSIWYG HTML editor that supports HTML code editing, image uploads, Markdown, and more

 

Now that we know what we need, letโ€™s do the following steps to create our project:

  1. Open Visual Studio and create a new project.
  2. Select the โ€œASP.NET Core Web App (Razor Pages) template. In our case, the project name is FroalaImageResizeDemo.
  3. Select โ€œ.NET 8.0 (Long Term Support)โ€ as the framework.
  4. Click โ€œCreateโ€.

 

Next, letโ€™s add the Froala Editor via CDN:

  1. Open the โ€œ_Layout.cshtmlโ€ file under the Pages > Shared directory.
  2. Add the Froala CDN links inside the <head> section.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/4.3.0/css/froala_editor.pkgd.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/4.3.0/js/froala_editor.pkgd.min.js"></script>

Once weโ€™ve included Froala in our project, we will be installing ImageMagick via NuGet Package Manager.ย 

  1. In the Solution Explorer, right-click the project name and select โ€œManage NuGet Packages.โ€
  2. Under the โ€œBrowseโ€ tab, search for โ€œMagick.NET-Q8-AnyCPUโ€ and click the install button.

Finally, letโ€™s create a folder where we can store the images. In the Solution Explorer, find the โ€œwwwrootโ€ folder. Create a new folder inside it named โ€œimages.โ€ Now that weโ€™ve configured our project setup, itโ€™s time to create our image resizing HTML code writer.

Making the HTML code writer

First, letโ€™s create a new page where we can initialize and load Froala Editor.

  1. Right-click the Pages folder.
  2. Select Add > New Item > Razor Page.
  3. Letโ€™s name it โ€œEditor.cshtml.โ€

 

Insert the following code to the newly created page:

 

@page
@model FroalaImageResizeDemo.Pages.EditorModel
@{
ย  ย  ViewData["Title"] = "Froala Image Resize Demo";
}

<h2 class="mt-5 mb-3">@ViewData["Title"]</h2>

<div id="editor">For this demo, we're resizing all uploaded images to 600 px by 300 px.</div>


<script>
ย  ย  new FroalaEditor('#editor', {
ย  ย  ย  ย  imageUploadURL: '',
ย  ย  ย  ย  heightMin: 600
ย  ย  });
</script>

 

This page will contain the Froala editor as well as a header. The <div> with the โ€œeditorโ€ ID is the container where weโ€™ll load Froala. On the other hand, imageUploadURL is a Froala image upload option that determines where the upload request is made. For now, letโ€™s leave that option blank, but weโ€™ll get back to it later.

 

We now have a dedicated page for our HTML code writer. However, itโ€™s still not reachable via navigation, so letโ€™s fix that by adding a link:

  1. Open โ€œ_Layout.cshtmlโ€ again.
  2. Add the following code snippet to the <ul> within the navbar section:

 

ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย  ย 

<li class="nav-item">
ย  ย  <a class="nav-link text-dark" asp-page="/Editor">Froala Editor</a>
</li>

ย 

 

Afterwards, try running the application by pressing F5 or the play button. You should now have a glimpse of the default ASP.NET Core application with a โ€œFroala Editorโ€ link on the navbar. Click on it, and youโ€™ll see Froala in action. You can now edit text, upload images, and perform other rich text actions. All thatโ€™s left now is to combine our HTML code writer with ImageMagick for image resizing.

 

Integrating ImageMagick for resizing images

To include ImageMagickโ€™s resizing feature, we need to first create a new controller:

  1. Right-click the Controllers folder (create one if it wasnโ€™t generated by the IDE).
  2. Select Add > New Item.
  3. Under the ASP.NET Core category, choose โ€œAPI Controller โ€“ Empty.โ€
  4. Name it โ€œFroalaApiController.csโ€ and click the add button.

 

Next, add the following code to the newly created controller:

 

using Microsoft.AspNetCore.Mvc;
using ImageMagick;

[Route("api/FroalaApi")]
[ApiController]
public class FroalaApiController : ControllerBase
{
ย  ย  [HttpPost("UploadImageResize")]
ย  ย  public IActionResult UploadImageResize()
ย  ย  {
ย  ย  ย  ย  // Check if the request contains files
ย  ย  ย  ย  if (Request.Form.Files.Count == 0)
ย  ย  ย  ย  {
ย  ย  ย  ย  ย  ย  return BadRequest("No files were uploaded.");
ย  ย  ย  ย  }

ย  ย  ย  ย  var file = Request.Form.Files[0];

ย  ย  ย  ย  if (file.Length > 0)
ย  ย  ย  ย  {
ย  ย  ย  ย  ย  ย  // Define the file path
ย  ย  ย  ย  ย  ย  var filePath = Path.Combine(Directory.GetCurrentDirectory(),ย  ย  ย  ย  "wwwroot", "images", file.FileName);

ย  ย  ย  ย  ย  ย  // Save the file to the server
ย  ย  ย  ย  ย  ย  using (var stream = new FileStream(filePath, FileMode.Create))
ย  ย  ย  ย  ย  ย  {
ย  ย  ย  ย  ย  ย  ย  ย  file.CopyTo(stream);
ย  ย  ย  ย  ย  ย  }

ย  ย  ย  ย  ย  ย  // Resize the image
ย  ย  ย  ย  ย  ย  using (var image = new MagickImage(filePath))
ย  ย  ย  ย  ย  ย  {
ย  ย  ย  ย  ย  ย  ย  ย  var resizeGeometry = new MagickGeometry(600, 600)
ย  ย  ย  ย  ย  ย  ย  ย  {
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  IgnoreAspectRatio = true
ย  ย  ย  ย  ย  ย  ย  ย  };
ย  ย  ย  ย  ย  ย  ย  ย  image.Resize(resizeGeometry);
ย  ย  ย  ย  ย  ย  ย  ย  image.Write(filePath); // Save the resized image
ย  ย  ย  ย  ย  ย  }

ย  ย  ย  ย  ย  ย  return Ok(new { link = $"/images/{file.FileName}" });
ย  ย  ย  ย  }

ย  ย  ย  ย  return BadRequest("Failed to upload image.");
ย  ย  }
}

 

Firstly, make sure to include โ€œusing ImageMagickโ€ to enable it. We then check whether a file was successfully uploaded from the request or not. Then, we define the file path where we store our images (in our case, under wwwroot > images). Afterwards, we resize the image by declaring a new MagickImage object with our desired dimensions (600ร—600 pixels). Lastly, we return an HTTP 200 status code along with the JSON containing the imageโ€™s URL on success. Froala will then display the image within the editor, and weโ€™re done!

 

 

Conclusion

Resizing images is a vital task for any application. For instance, we might need to limit image resolution for display purposes (e.g., email or blog images). We might also need to minimize image size for efficiency and cost reduction. However, image handling can be a pain sometimes. Fortunately, there are dozens of tools like ImageMagick that can help us easily accomplish that, as Iโ€™ve shown you in this HTML code writer demo.

 

By combining .NET, Froala, and ImageMagick, you can streamline the entire process of implementing image resizing in your applications. For your own projects, using the same tools, you can even take it up a notch. For example, you can add image quality enhancement, file type and size validation, autosaving, and more to make your application more robust. Now, itโ€™s your turn to sprinkle some (Image)magic(K) on your projects!

Posted on October 17, 2024

Aaron Dumon

Aaron Dumon is an expert technical writer focusing on JavaScript WYSIWYG HTML Editors.

No comment yet, add your voice below!


Add a Comment

Your email address will not be published. Required fields are marked *