Example of Image in ASP.NET MVC Rich Text Editor Control
This sample demonstrates the option to insert an image into the Rich Text Editor content. Click the image button from the toolbar item to insert the image.
Properties
@Html.UiRichTextEditor(new UiRichTextEditorOptions
{
Id = "imageEditor",
QuickToolbarSettings = new UiRichTextQuickToolbar { Image = (List<string>)ViewData["Image"] },
InsertImageSettings = new UiRichTextImageSettings { SaveUrl = Url.Action("SaveImage"), MaxFileSize = 2000000 },
Value = (string)ViewData["RTEValue"]
})
@Html.UiRichTextEditor(new UiRichTextEditorOptions
{
Id = "imageEditor",
QuickToolbarSettings = new UiRichTextQuickToolbar { Image = (List<string>)ViewData["Image"] },
InsertImageSettings = new UiRichTextImageSettings { SaveUrl = Url.Action("SaveImage"), MaxFileSize = 2000000 },
Value = (string)ViewData["RTEValue"]
})
<div class="demo-property-panel">
<h3>Properties</h3>
<div class="demo-property-row"><label for="autoUrl">EnableAutoUrl</label><input id="autoUrl" type="checkbox" /></div>
<div class="demo-property-row">
<label for="format">Format Option</label>
<select id="format">
<option value="Base64">Base64</option>
<option value="Blob">Blob</option>
</select>
</div>
</div>
<script>
document.getElementById('autoUrl').addEventListener('change', function (e) {
window.Lumen.get('imageEditor').setSettings({ enableAutoUrl: e.target.checked });
});
document.getElementById('format').addEventListener('change', function (e) {
window.Lumen.get('imageEditor').setSettings({ insertImageSettings: { saveFormat: e.target.value } });
});
</script>
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.IO;
using System.Web;
using System.Linq;
using System.Web.Mvc;
using Lumen.UI.Mvc;
namespace YourApp.Controllers
{
public class RichTextEditorController : Controller
{
// The page is Views/RichTextEditor/Image.cshtml; it draws what ViewData holds.
// The files under ~/Content are the demo's own sample files: put yours at those paths, or change the addresses.
public ActionResult Image()
{
ViewData["Image"] = new List<string> { "Replace", "Align", "Caption", "Remove", "WrapText", "InsertLink", "OpenImageLink", "|", "EditImageLink", "RemoveImageLink", "Display", "AltText", "Dimension", "RotateLeft", "RotateRight" };
ViewData["RTEValue"] = "<h2>Insert Image in Rich Text Editor!<br></h2><p>You can insert and edit images within this editor. Click inside the editor and use the <strong>image tool</strong> to add an image.</p>" +
"<h5>What You Can Do</h5><ul><li><strong>Insert Images:</strong> Upload images from local storage or provide an image URL.</li>" +
"<li><strong>Resize & Drag:</strong> Easily adjust image dimensions with the handle at the corner of the image.</li>" +
"<li><strong>Align Images:</strong> Set images to align <strong>left, center, or right</strong>, or let the text wrap around them.</li>" +
"<li><strong>Caption Support:</strong> Add captions to describe your images.</li>" +
"<li><strong>Replace & Remove:</strong> Change or delete images as needed.</li></ul><h5>Try It Out!</h5>" +
"<p><img alt=\"The Lumen logo\" src=\"" + Url.Content("~/Content/images/LumenLogo.png") + "\" width=\"300\"></p>";
return View();
}
/// <summary>The Image sample's uploads: kept in memory (the 50 newest), as a demo needs no storage of its own.</summary>
private static readonly ConcurrentDictionary<string, KeyValuePair<DateTime, byte[]>> Images = new ConcurrentDictionary<string, KeyValuePair<DateTime, byte[]>>();
private const int MaxImageBytes = 2000000;
/// <summary>
/// The Image sample's upload action (InsertImageSettings.SaveUrl): a PNG, JPEG, GIF or WebP file of up to 2 MB, known by its first
/// bytes (not its name), answered with { url }. Anything else is refused with 400. The file comes as UploadFiles (the editor's field,
/// as Syncfusion's) or file.
/// </summary>
[HttpPost]
[ValidateJsonAntiForgeryToken]
public ActionResult SaveImage(HttpPostedFileBase file, HttpPostedFileBase uploadFiles)
{
file = file ?? uploadFiles;
if (file == null || file.ContentLength <= 0 || file.ContentLength > MaxImageBytes)
{
return new HttpStatusCodeResult(400, "An image of up to 2 MB is needed.");
}
var bytes = new byte[file.ContentLength];
int read = 0;
while (read < bytes.Length)
{
int n = file.InputStream.Read(bytes, read, bytes.Length - read);
if (n <= 0) { break; }
read += n;
}
if (read != bytes.Length || ImageType(bytes) == null)
{
return new HttpStatusCodeResult(400, "Only PNG, JPEG, GIF and WebP images are taken.");
}
string id = Guid.NewGuid().ToString("N");
Images[id] = new KeyValuePair<DateTime, byte[]>(DateTime.UtcNow, bytes);
foreach (string old in Images.OrderByDescending(i => i.Value.Key).Skip(50).Select(i => i.Key).ToList()) { KeyValuePair<DateTime, byte[]> gone; Images.TryRemove(old, out gone); }
return Json(new { url = Url.Action("Image", new { id }) });
}
/// <summary>An uploaded image, by the id SaveImage gave it.</summary>
public ActionResult Image(string id)
{
KeyValuePair<DateTime, byte[]> image;
if (id == null || !Images.TryGetValue(id, out image)) { return HttpNotFound(); }
Response.Headers["X-Content-Type-Options"] = "nosniff";
return File(image.Value, ImageType(image.Value));
}
private static string ImageType(byte[] b)
{
if (b.Length > 8 && b[0] == 0x89 && b[1] == 0x50 && b[2] == 0x4E && b[3] == 0x47) { return "image/png"; }
if (b.Length > 3 && b[0] == 0xFF && b[1] == 0xD8 && b[2] == 0xFF) { return "image/jpeg"; }
if (b.Length > 6 && b[0] == 0x47 && b[1] == 0x49 && b[2] == 0x46 && b[3] == 0x38) { return "image/gif"; }
if (b.Length > 12 && b[0] == 0x52 && b[1] == 0x49 && b[2] == 0x46 && b[3] == 0x46 && b[8] == 0x57 && b[9] == 0x45 && b[10] == 0x42 && b[11] == 0x50) { return "image/webp"; }
return null;
}
}
}
@* Install once: Install-Package Lumen.UI.Mvc (or: dotnet add package Lumen.UI.Mvc) *@
@* Views/Web.config: <add namespace="Lumen.UI.Mvc" /> *@
@* Views/Shared/_Layout.cshtml *@
<head>
@Html.UiStyles()
<link rel="stylesheet" href="~/Content/site.css" />
</head>
<body>
@RenderBody()
@Html.UiScripts()
@RenderSection("scripts", required: false)
</body>
@* Rich Text Editors with a DataUrl: @Html.AntiForgeryToken() on the page and [HttpPost, ValidateJsonAntiForgeryToken] on the action. *@
Image tools are used to insert an image into the Rich Text Editor; click on the image to easily customize it using the quick toolbar. The quick toolbar has the following items:
Replace– To replace the image with some other image.Align– Align the image with left, center and right (the image gets a paragraph of its own).Image captions– Set the captions for the image.Change size– Modify the width of the image.Delete– Delete the image.Link– Provide the link to the image, open it, edit it or remove it.Display– Display the image inline, or with a break (in a paragraph of its own).Alternate text– Provide the alternative text for the image if the image is not present in the location.Rotate left and right– Turn the picture a quarter. The pixels are drawn again, so the HTML needs no style; a picture from another site cannot be rotated.Resize– To resize the image dimension with the resize handle.WrapText– Controls text flow around an image, with left and right options.
Quick commands are opened as a toolbar on clicking the corresponding element. The commands are passed as a string collection to the image,
text and link lists of the QuickToolbarSettings property. EnableAutoUrl makes a link typed without a scheme
(www.example.com) work as an address. Format Option (InsertImageSettings.SaveFormat): with Blob a picked file
is shown from a blob address while it is edited; the editor’s value always holds the data address, because a blob address dies with the page.