C# copy paste an image region into another image

teodron picture teodron · Mar 8, 2012 · Viewed 33.6k times · Source

I am trying to write an utility class that permits automatic resizing of images that are tilebale. Let's say there is a srcBitmap from where I copy a region given by a Rectangle srcRegion. I then want to paste (pixel information wise) that region into another image called Bitmap destBitmap, in a destination region Rectangle destRegion. I know how to get the region from the source and put it into a Bitmap object, but I haven't yet been able to find how to actually paste a Bitmap object in a certain region, inside another, bigger Bitmap object.

Is there a quick way to do this? (without GDI and without delving into the byte array of the Bitmaps). Here is the snippet that should clarify my goal

    private static void CopyRegionIntoImage(Bitmap srcBitmap, Rectangle srcRegion, Bitmap destBitmap, Rectangle destRegion)
    {
        // get the required region from the destination
        Bitmap region = Copy(srcBitmap, srcRegion);
    }

Answer

Amen Ayach picture Amen Ayach · Mar 8, 2012

Use this :

    public static void CopyRegionIntoImage(Bitmap srcBitmap, Rectangle srcRegion,ref Bitmap destBitmap, Rectangle destRegion)
    {
        using (Graphics grD = Graphics.FromImage(destBitmap))            
        {
            grD.DrawImage(srcBitmap, destRegion, srcRegion, GraphicsUnit.Pixel);                
        }
    }