Search code examples
c#formswinformsvisual-studiographic

Windows Forms C#, Image editing


I'm currently working on an application, to automate the generation of tilesets. Actually my question is fairly simple. I'm having trouble with seperating the file into tiles. Is it possible to create seperate images out of a PictureBox or is there another, more effective way? I want to cut the graphic into tiles, to rearrange them.


Solution

  • You can get a sub-image from a PictureBox relatively easily is the image is just a bitmap. You can use the bitmap classes Clone() method, which takes a Rectangle and PixelFormat.

    Bitmap image = pictureBox.Image;
    Bitmap subImage = image.Clone(new Rect(0,0,64,64), image.PixelFormat);
    

    The subimage in this case would start at position (0,0) in the image and by 64x64 in size

    In order to rearrange your tiles you can print them back onto the PictureBox like so:

    Graphics g = Graphics.FromImage(image);
    g.drawImage(subImage, 64, 64);
    pictureBox.Image = image;
    

    This will draw subImage into the image at (64,64) we grabbed from the picturebox, image, earlier and then set the PictureBox image to the edited one.