Duncan Palmer
Duncan Palmer

Reputation: 2913

Get a certain square region of a bitmap

Hey guys I was wondering if there is a way to get a certain region of a bit map? I'm trying to make a tileset cutter and I need it to iterate through the loaded tileset and cut the image up into xscale * yscale images then save them individually. I am currently using this for my loop for the cutting procedure.

         int x_scale, y_scale, image_width, image_height;

         image_width = form1.getWidth();
         image_height = form1.getHeight();
         x_scale = Convert.ToInt32(xs.Text);
         y_scale = Convert.ToInt32(ys.Text);

         for (int x = 0; x < image_width; x += x_scale)
         {
             for (int y = 0; y < image_height; y += y_scale)
             {
                 Bitmap new_cut = form1.getLoadedBitmap();//get the already loaded bitmap


             }
         }

So is there a way I can "select" a part of the bitmap new_cut and then save that portion?

Upvotes: 2

Views: 2161

Answers (2)

max
max

Reputation: 34427

You can use LockBits method to get a description of bitmap rectangular region. Something like

// tile size
var x_scale = 150;
var y_scale = 150;
// load source bitmap
using(var sourceBitmap = new Bitmap(@"F:\temp\Input.png"))
{
    var image_width = sourceBitmap.Width;
    var image_height = sourceBitmap.Height;
    for(int x = 0; x < image_width - x_scale; x += x_scale)
    {
        for(int y = 0; y < image_height - y_scale; y += y_scale)
        {
            // select source area
            var sourceData = sourceBitmap.LockBits(
                new Rectangle(x, y, x_scale, y_scale),
                System.Drawing.Imaging.ImageLockMode.ReadOnly,
                sourceBitmap.PixelFormat);
            // get bitmap for selected area
            using(var tile = new Bitmap(
                sourceData.Width,
                sourceData.Height,
                sourceData.Stride,
                sourceData.PixelFormat,
                sourceData.Scan0))
            {
                // save it
                tile.Save(string.Format(@"F:\temp\tile-{0}x{1}.png", x, y));
            }
            // unlock area
            sourceBitmap.UnlockBits(sourceData);
        }
    }
}

Upvotes: 4

Oded
Oded

Reputation: 499132

You can use the SetClip methods of the Graphics object to clip regions of the image into new images.

Some of the overloads take a Rectangle struct that represents the bounding box for what to clip in the image.

Upvotes: 0

Related Questions