Replacing ImageSharp with Magick.NET on Optimizely CMS 12
We had a situation recently where a routine NuGet package bump turned into replacing our whole image resizer. Here's how that happened and what we learned along the way.
The license problem
Our build started warning about six known vulnerabilities in SixLabors.ImageSharp 3.1.12, which is the version EPiServer.ImageLibrary.ImageSharp 2.0.6 pulls in. The fixes ship in 3.2.0, but 3.2.0 fails Release builds with "No Six Labors license found" unless you set a license key.
So I read the license page, and then I opened a support ticket with Optimizely to ask what we were allowed to do. The answer was reasonable. If ImageSharp only reaches your solution through Optimizely's package, you don't need your own license. If your own code references it directly, you do. That lines up with how the package works, too: the license check only runs in projects that reference ImageSharp directly, so the transitive copy doesn't break your build.
Our code referenced it directly. We called Image.Load and Image.Identify in a few places, and we used SixLabors.ImageSharp.Web for on-the-fly resizing.
I could have bought the license. Instead I asked whether we still needed ImageSharp in our own code at all. We already used Magick.NET to compress uploaded photos, so it was already in the solution. Dropping ImageSharp turned out to be a bigger job than I expected, but not as bad as I feared.
What ImageSharp.Web was doing for us
It turns out it was doing more than I'd noticed. You add a query string to a media URL, like ?width=400&height=300&mode=crop, and you get back a resized image. Behind that it parses the command, finds the file, resizes it, caches the result, sets the cache headers and answers conditional requests.
When you replace it, all of that is on you. Here's what we had to rebuild:
- Parse the query string and clamp it to sane limits.
- Check that the visitor can read the media item, so resizing doesn't become a way around CMS access rights.
- Cache the processed image somewhere shared, since we run several instances.
- Send an ETag and answer If-None-Match with a 304.
- Don't resize the same image five times when five visitors ask for it at once.
- Don't let a flood of resize requests eat all the CPU.
I worked through the design with Claude, and Claude wrote most of the code and tests. We ended up with about 200 lines of middleware, about 270 lines of transformer and roughly 560 lines of tests. The rest of the pull request was removing package references and a lot of Razor changes.
The middleware
The parts I'd reuse are the cache key and the throttling. The key is a hash of everything that changes the output, with a version prefix so we can invalidate every cached image by changing one character:
private static string BuildKey(MediaData media, ImageCommand command)
{
var raw = $"v2|{media.ContentGuid}|{media.BinaryData.ID}|{command.Width}|{command.Height}|{command.Mode}|{command.Format}";
return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(raw))).ToLowerInvariant();
}
Because the key includes the binary ID, replacing the file in the CMS produces a new key, so nothing needs purging. The same key doubles as the ETag.
Concurrent requests for the same key share one piece of work:
var work = InFlight.GetOrAdd(key, _ => new Lazy<Task<ProcessedImage>>(() => TransformAndStoreAsync(key, media, command)));
A SemaphoreSlim limits how many transforms run at once. That's half the CPU count, with a minimum of two. If a request can't get a slot within ten seconds, we serve the original image with Cache-Control: no-store instead of failing, so the visitor still gets a picture.
The cache lives in Azure Blob Storage. Writes use IfNoneMatch = ETag.All, so when two instances finish the same image, the second one gets a 409 or 412 and just moves on.
Magick.NET gotchas
It'll try to decode almost anything. ImageMagick reads a lot more than photos, so we read the image header first with MagickImageInfo.ReadCollection and reject anything that isn't on a short list of raster formats. We also set hard limits on source pixels, output pixels and total animated pixels. Anything that fails those checks gets a 404.
Decode small. For a JPEG that will shrink to half size or less, you can give the decoder a size hint with JpegReadDefines, and it skips work it doesn't need.
The small stuff adds up. We strip the EXIF, IPTC and XMP profiles and auto-orient. We put JPEGs with transparency on a white background, quantize indexed PNGs back to 256 colors, and keep WebP lossless when the source was lossless. ImageSharp.Web had been doing all of that for us without us noticing.
DllNotFoundException can be a path problem. If Magick.NET throws a DllNotFoundException about a missing dependency, check your path length before anything else. I hit this in an early test project where the folder was nested so deep that the native DLL's full path went over Windows' 260-character MAX_PATH limit.
Results so far
So far so good, with about two and a half days of data on Production:
- No image 5xx errors across roughly 365,000 resize requests.
- A median response time of 23 to 36 ms on the last two days, with the 95th percentile under a second.
- CPU stayed low, with the average well under 20 percent.
Memory is the number I'm watching. The first day peaked near 19 GB on one instance, against a peak near 15 GB on the old pipeline. Since then the peak has settled around 14 to 15 GB, so it's back to about where it was. I haven't tuned anything yet. If it becomes a problem, I'll lower the concurrency and the source-pixel limit first.
Claude also tried resizing in linear light, which is technically the more correct way to do it. It cost about 65 percent more CPU per transform for a one to three percent difference in the result, so we didn't use it.
One thing I'd do differently: the old cache blobs sit at the root of the container with no prefix. There are close to two million of them now. We can't set a lifecycle rule on that storage account, and even if we could, a rule matches on a prefix, so it couldn't tell those blobs apart from the media files in the same container. The new cache lives under an img-cache/ prefix, so if you're setting up a blob cache, give it a prefix from day one.
What's left
EPiServer.ImageLibrary.ImageSharp is still in the solution because Optimizely's own packages need it. Our code doesn't reference ImageSharp at all anymore, which is the setup Optimizely told us doesn't need a license.
Rolling back is just a revert. I'd like a few more weeks of data before I call this done.
Has anyone else moved off ImageSharp on a CMS 12 site? I'd love to hear what you used instead, and whether your memory numbers looked like mine. Let me know in the comments.
Comments