Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two images?

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

like image 660
Leonardo Avatar asked Dec 01 '22 14:12

Leonardo


1 Answers

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;
like image 92
tocsoft Avatar answered Dec 18 '22 07:12

tocsoft