---
title: "Crop an HTML image with object-fit: cover in C#"
url: https://recursiveai.org/onerender/cookbook/crop-image-with-css-object-fit-in-html-render/
description: "Crop an HTML image to a square with CSS object-fit: cover and export the layout to PNG in C#. Compare contain and a left-aligned crop."
version: "1.4.0"
---

# 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.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneRender.Image) · [GitHub](https://github.com/recursive-ai-oss/onerender-csharp) · [Docs](https://recursiveai.org/onerender/docs/) · [Download example (.zip)](https://recursiveai.org/onerender/cookbook/crop-image-with-css-object-fit-in-html-render/crop-image-with-css-object-fit-in-html-render.zip)

A cover crop fills the frame without stretching the image.

```shell
dotnet add package RecursiveAI.OneRender.Image
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

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

```csharp
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](https://recursiveai.org/onerender/cookbook/crop-image-with-css-object-fit-in-html-render/crop-image-with-css-object-fit-in-html-render.zip), 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.

```csharp
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;
```

## Related recipes

- [Render HTML to PNG in C#](https://recursiveai.org/onerender/cookbook/html-to-png/)
- [Load images and stylesheets when rendering HTML](https://recursiveai.org/onerender/cookbook/load-html-render-resources/)

## 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](https://www.w3.org/TR/css-images-3/#the-object-fit) 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](https://www.w3.org/TR/css-images-3/#the-object-position) 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.
