Recursive AI

Crop an HTML image with object-fit: cover in C#

OneRender is a free, open-source HTML and CSS rendering library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

A cover crop fills the frame without stretching the image.

Terminal
dotnet add package RecursiveAI.OneRender.Image

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

Use stripes.png from the ZIP, or save any PNG as stripes.png.

C#
using OneRender.Image;
string html = """
<body style="margin:0;background:white">
<img src="stripes.png" style="object-fit:cover;
  width:60px;height:60px;display:block;
  image-rendering:pixelated">
</body>
""";
byte[] png = File.ReadAllBytes("stripes.png");
const string root = "https://example.com/";
var options = new HtmlRenderOptions {
    Width = 60, Height = 60, BaseUrl = root,
    Resources = url => url == root + "stripes.png"
        ? png : null
};
var image = HtmlRender.ToImage(html, options);
File.WriteAllBytes("cover.png", image.ToPng());
Console.WriteLine("Saved cover.png");

Writes cover.png, a 60 × 60 px square showing the center stripe.

Text
Saved cover.png

Unzip the example, then dotnet run.

Use stripes.png from the ZIP. It is a 180 × 60 px sample: three 60 px bands, red, lime green, and blue, left to right.

The full program

The program renders the same markup three ways. It prints the RGB values near the top and at the center so you can tell a white gap from a solid crop. The Resources callback returns the local PNG bytes; it doesn’t fetch the placeholder URL.

C#
using OneRender.Image;
string html = """
<body style="margin:0;background:white">
<img src="stripes.png" style="object-fit:cover;
  width:60px;height:60px;display:block;
  image-rendering:pixelated">
</body>
""";
byte[] png = File.ReadAllBytes("stripes.png");
const string root = "https://example.com/";
var options = new HtmlRenderOptions {
    Width = 60, Height = 60, BaseUrl = root,
    Resources = url => url == root + "stripes.png"
        ? png : null
};
 
Render("cover.png", html);
Render("contain.png", html.Replace("fit:cover", "fit:contain"));
Render("left.png", html.Replace("fit:cover;",
    "fit:cover;object-position:left center;"));
 
void Render(string file, string markup)
{
    var image = HtmlRender.ToImage(markup, options);
    File.WriteAllBytes(file, image.ToPng());
    Console.WriteLine($"{file}: {image.Width} x {image.Height}");
    Console.WriteLine($"  (30,5) {Rgb(30, 5)}; (30,30) {Rgb(30, 30)}");
 
    string Rgb(int x, int y)
    {
        int i = (y * image.Width + x) * 4;
        return $"#{image.Pixels[i]:X2}{image.Pixels[i+1]:X2}{image.Pixels[i+2]:X2}";
    }
}

dotnet run prints:

Text
cover.png: 60 x 60
  (30,5) #00FF00; (30,30) #00FF00
contain.png: 60 x 60
  (30,5) #FFFFFF; (30,30) #00FF00
left.png: 60 x 60
  (30,5) #FF0000; (30,30) #FF0000

If the image is missing, check that Resources returns bytes for the resolved URL, not just the bare filename.

Variations

Show the whole image, with white space above and below. In the HTML string, replace the fit declaration on the <img> with:

CSS
object-fit: contain;

Keep the square filled, but show the left (red) stripe instead of the center. Add both declarations to the same <img>:

CSS
object-fit: cover;
object-position: left center;

The short answer

Give the HTML <img> a fixed width and height and set object-fit: cover on it. Supply the image bytes through HtmlRenderOptions.Resources, render with HtmlRender.ToImage, and save the PNG. The crop affects what is visible in the rendered page. It doesn’t edit stripes.png or change the layout size of the element.

What’s the difference between CSS object-fit cover and contain?

Both preserve the image’s proportions. cover scales until both dimensions fill the box and clips whatever doesn’t fit. Here the source is already as tall as the square, so the renderer only needs to crop the sides: the centered result is the lime band. contain scales until the whole image fits. In this example the 180 × 60 px source scales to 60 × 20 px, leaving 20 px of white page above it and 20 px below. Choose cover when a thumbnail must fill its frame. Choose contain when you can’t lose part of the subject. The CSS Images specification defines both sizing rules.

How do you change which part of a CSS image is cropped?

Keep cover and set object-position to align the part you want to keep. Here the surplus is all horizontal. left center holds the left edge against the box, so you see red instead of lime. The vertical center has no visible effect because the image already fits the full height after scaling. See the CSS position rules for how alignment works when the scaled image overflows the box.

Why doesn’t object-fit crop my image?

Check both the element and the page. object-fit applies to the image inside the <img> box. If the element keeps the source aspect ratio, there’s nothing to crop; giving the page a square viewport is not the same as giving the image a square box. Also check the resource callback: if the renderer never gets the PNG, it has no image to fit. If you’re sizing a CSS background rather than an HTML <img>, use background-size instead.

All onerender recipes