c# – Glue, merge photos (jpeg map)

Question:

There are many files of one map COLUMN_LINE.jpeg all files are the same size – 256х256 px .

How can I merge them into one jpeg file?

PS: If the input files are 001_001.jpeg 001_002.jpeg 002_001.jpeg 002_001.jpeg , then the resulting map.jpeg will be 512х512 px .


I'm sorry. Maybe I didn't describe the problem clearly enough.

I clarify: there can be a LOT of input files (for example, 100×100=10,000 images). And you need to run it on 4 GB of RAM (well, given that the system must somehow work).


Haven't tested at 10,000. Just uploading so many pictures is stressful. But I will share the code with which I made the gluing.

And I messed up – I have .png , not .jpeg . But the principle is the same. There is a difference, but who needs to understand.

using System;
using System.IO;
using System.Drawing;

class IMGhelper
{
    public int NeedCOLUMN; // я знаю сколько должно быть колонок
    public int NeedLINE; // я знаю сколько должно быть строк
    // потому что я сначала задал программе скачать это кол-во колонок и строк

    private string[,] m_filesExist; // тут будут хранится пути ко всем картинкам

    private void getFiles() // будьте осторожны! Этот метод работает в МОИХ условиях
    // У вас тут может выпасть ИСКЛЮЧЕНИЕ!
    {
        m_filesExist = new string[NeedCOLUMN, NeedLINE];
        string[] dirs = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "Map\\", "*.png"); // маленькие картинки в папке Map
        foreach (string dir in dirs)
        {
            // мои файлы называются ххх_ххх.png (например 017_010.png)
            string[] tmp = Path.GetFileName(dir).Split('.')[0].Split('_');

            int col = int.Parse(tmp[0]); // тут 017
            int row = int.Parse(tmp[1]); // тут 010
            m_filesExist[col, row] = dir;
        }
    }

    public void ImgCombine()
    {
        readFiles();
        // Создаем новый image нужного размера (это будет объединенный image)
        Image img = new Bitmap(256 * NeedCOLUMN, 256 * NeedLINE);// у меня каждое изображение 256x256 px

        // Делаем этот image нашим контекстом, куда будем рисовать
        Graphics g = Graphics.FromImage(img);

        // рисуем существующие маленькие image в созданный нами большой image
        for (int c = 0; c < NeedCOLUMN; c++)
        {
            for (int r = 0;r < NeedLINE; r++)
            {
                g.DrawImage(Image.FromFile(m_filesExist[c,r]), new Point(256*c, 256*r));
            }
        }

        // Записываем обобщенный image в файл рядом с исполняемым файлом

        img.Save("output.png", System.Drawing.Imaging.ImageFormat.Png);
    }
}

And call

static void Main(string[] args)
{
    IMGhelper IH = new IMGhelper();
    //у меня 600 изображений из них должно получится 20 колонок и 30 строк
    IH.NeedCOLUMN = 20;
    IH.NeedLINE = 30;

    IH.ImgCombine();
}

Answer:

Like that:

  1. Create a Bitmap of the right size
  2. Graphics.FromBitmap
  3. At the desired coordinates, you draw pieces through Graphics.DrawImageUnscaled
  4. Save Bitmap to file
Scroll to Top