4

Using ImageSharp for .Net core, how can I combine 2 images side by side? e.g.: make 2 100x150px become 1 100x300px (or 200x150px)

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Leonardo
  • 10,737
  • 10
  • 62
  • 155

1 Answers1

24

You can draw your 2 source images onto a new image of the correct dimensions using this code.

It takes your 2 source images, resizes them down to the exact dimensions required, then draws each of them onto a third image ready for saving.

using (Image<Rgba32> img1 = Image.Load<Rgba32>("source1.png")) // load up source images
using (Image<Rgba32> img2 = Image.Load<Rgba32>("source2.png"))
using (Image<Rgba32> outputImage = new Image<Rgba32>(200, 150)) // create output image of the correct dimensions
{
    // reduce source images to correct dimensions
    // skip if already correct size
    // if you need to use source images else where use Clone and take the result instead
    img1.Mutate(o => o.Resize(new Size(100, 150))); 
    img2.Mutate(o => o.Resize(new Size(100, 150)));

    // take the 2 source images and draw them onto the image
    outputImage.Mutate(o => o
        .DrawImage(img1, new Point(0, 0), 1f) // draw the first one top left
        .DrawImage(img2, new Point(100, 0), 1f) // draw the second next to it
    );

    outputImage.Save("ouput.png");
}

This code assumes you have these usings in scope

using SixLabors.ImageSharp.Processing.Transforms;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing.Drawing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.Primitives;
tocsoft
  • 1,709
  • 16
  • 22
  • 1
    as of 1.0 beta 6, this should read "outputImage.Mutate(o => o .DrawImage(img1,new Point(0, 0), 1f) // draw the first one top left .DrawImage(img2,new Point(100, 0), 1f) // draw the second next to it" the last 2 parameters are swapped – TheColonel26 Jul 02 '19 at 20:41
  • @TheColonel26 thanks for noticing (the api had change), I've updated the sample code. – tocsoft Jul 02 '19 at 20:46
  • I'm stilling getting an issue though that I don't under stand. I have tried newImage.Mutate(o => o.DrawImage(leftImage, new Point(0, 0), 1f)); but I am getting a cannot convert error "Argument 3: cannot convert from 'System.Drawing.Point' to 'SixLabors.ImageSharp.PixelFormats.PixelColorBlendingMode'" there is clearly an extension method in the API that uses this signature though. – TheColonel26 Jul 02 '19 at 20:49
  • 1
    Point is an instance of `SixLabors.Primitives.Point`. You seems to have a `System.Drawing` using statement too if that's the case you are going to have to either alias SixLabors.Primitives.Point to something else or just use the full namespace when newing up. – tocsoft Jul 02 '19 at 20:53