Search code examples
c#.netimagebitmappng

C#.NET - Combine multiples .png in one Bitmap (.bmp)


I have multiples images.png (with names) stored on a folder. From code (C#) I want to create a rectangle bitmap (with transparent background not white) where all the images are embeded. Something like this:

enter image description here

How can I do this?


Solution

  • If you are using .NET Framework I would suggest taking a look at GDI+. It allows you to very easily draw shapes and other images without much work:

    // Create an image of your desired size
    var bitmap = new Bitmap(1000, 1000);
    using (var g = Graphics.FromImage(bitmap))
    {
        // Load another image and draw it at a certain position
        var otherImage = Bitmap.FromFile(@"otherimage.png");
        g.DrawImage(otherImage, new Point(60, 10));
    }
    
    bitmap.Save(@"output.bmp");
    

    EDIT: Seems I was wrong and you can now use GDI+ in .NET so you should not need the inefficient solution below.

    If you are using .NET, you can still use Bitmap by referencing System.Drawing.Common, but you won't get GDI+. . This makes the manipulation a bit harder as you only have GetPixel/SetPixel by default. So basic copying is easy to implement but anything related to stretching, drawing lines etc. is going to be work. If you want to do this you should look for image manipulation libraries for .NET.

    For the case you stated, it seems that simple copying is enough:

    var bitmap = new Bitmap(1000, 1000);
    var otherImage = (Bitmap)Image.FromFile(@"otherImage.png");
    CopyTo(otherImage, bitmap, 60, 10);
    
    void CopyTo(Bitmap source, Bitmap destination, int offsetX, int offsetY)
    {
        for (var x = 0; x < source.Width; x++)
        for (var y = 0; y < source.Height; y++)
        {
            destination.SetPixel(x + offsetX, y + offsetY, source.GetPixel(x, y));
        }
    }
    
    bitmap.Save(@"output.bmp");
    

    Either way, you need to do a bit of layouting to determine the right size of the final image and to position the images correctly but it should get you started.