System.Drawing.Bitmap.Clone C# (CSharp) Method

Clone() public method

Creates a copy of the section of this Bitmap defined by Rectangle structure and with a specified PixelFormat enumeration.
public Clone ( Rectangle rect, PixelFormat pixelFormat ) : Bitmap
rect Rectangle Rect.
pixelFormat PixelFormat Pixel format.
return Bitmap
        public Bitmap Clone(Rectangle rect, PixelFormat pixelFormat)
        {
            if (rect.Width == 0 || rect.Height == 0)
                throw new ArgumentException ("Width or Height of rect is 0.");

            var width = rect.Width;
            var height = rect.Height;

            var tmpImg = new Bitmap (width, height, pixelFormat);

            using (Graphics g = Graphics.FromImage (tmpImg)) {
                g.DrawImage (this, new Rectangle(0,0, width, height), rect, GraphicsUnit.Pixel );
            }
            return tmpImg;
        }

Usage Example

        public void AddImage(BackgroundImageClass image)
        {
            var imageBytes = webClientWrapper.DownloadBytes(image.ImageUrl);
            Bitmap bitmap = null;
            using (var originalBitmap = new Bitmap(new MemoryStream(imageBytes)))
            {
                using (var writer = new SpriteWriter(image.Width ?? originalBitmap.Width, image.Height ?? originalBitmap.Height))
                {
                    var width = image.Width ?? originalBitmap.Width;
                    if (width > originalBitmap.Width)
                        width = originalBitmap.Width;
                    var height = image.Height ?? originalBitmap.Height;
                    if (height > originalBitmap.Height)
                        height = originalBitmap.Height;
                    var x = image.XOffset.Offset < 0 ? Math.Abs(image.XOffset.Offset) : 0;
                    var y = image.YOffset.Offset < 0 ? Math.Abs(image.YOffset.Offset) : 0;

                    writer.WriteImage(originalBitmap.Clone(new Rectangle(x, y, width, height), originalBitmap.PixelFormat));
                    bitmap = writer.SpriteImage;
                    if ((originalBitmap.Width * originalBitmap.Height) > (bitmap.Width * bitmap.Height))
                        Size += writer.GetBytes("image/png").Length;
                    else
                        Size += imageBytes.Length;
                }
            }
            images.Add(bitmap);
            Width += bitmap.Width;
            if (Height < bitmap.Height) Height = bitmap.Height;
        }
All Usage Examples Of System.Drawing.Bitmap::Clone