How to: Copy Images
[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]
The .NET Compact Framework does not support the Image.Clone method, but you can still copy images and parts of images. The following examples show how to do the following:
Define a method to create a bitmap.
Define an overloaded method to copy a bitmap or to copy part of a bitmap.
Call these methods and draw the images to the screen by overriding the OnPaint method of your form.
To create a bitmap
This method creates a bitmap for demonstration purposes.
' Creates a bitmap for copying. Function CreateBitmap(sideSize As Integer) As Bitmap Dim bmp As New Bitmap(sideSize, sideSize) Dim g As Graphics = Graphics.FromImage(bmp) g.FillEllipse(New SolidBrush(Color.Red), 0, 0, sideSize, sideSize) g.DrawLine(New Pen(Color.Black), 0, 0, sideSize, sideSize) g.DrawLine(New Pen(Color.Black), sideSize, 0, 0, sideSize) g.Dispose() Return bmp End Function
To clone a bitmap
This method overload takes a source bitmap as a parameter and returns the bitmap as a copy.
To copy part of a bitmap
This method overload takes a Rectangle as a parameter to determine the dimensions of the part of the bitmap to return.
To create, copy, and draw the bitmaps
This OnPaint method overload calls the methods to create a bitmap and then clone and copy a part of it. It also saves the cloned bitmap to a file.
' Draws the bitmaps on the form. Protected Overrides Sub OnPaint(e As PaintEventArgs) Dim arialFont As Font Dim blackBrush As Brush arialFont = New Font("Arial", 10, FontStyle.Regular) blackBrush = New SolidBrush(Color.Black) ' Set the size of the sides of the bitmap, ' and get one-third of it for the center bitmap. Dim sidesize As Integer = 75 Dim third As Integer = CInt(sidesize / 3) ' Create bitmap. Dim source As Bitmap = CreateBitmap(sidesize) ' Copy entirely as a clone. Dim clone As Bitmap = CopyBitmap(source) ' Copy the center part of the bitmap. Dim center As Bitmap = _ CopyBitmap(source, New Rectangle(third, third, third, third)) ' Save the bitmap to a file. clone.Save("newbitmap.bmp", ImageFormat.Bmp) ' Draw the source, clone, and partial ' bitmaps vertically down the screen. Dim y As Integer = 10 e.Graphics.DrawString("source bitmap:", ArialFont, BlackBrush, 10, y) y += 20 e.Graphics.DrawImage(source, 10, y) y += source.Height + 10 e.Graphics.DrawString("clone bitmap:", ArialFont, BlackBrush, 10, y) y += 20 e.Graphics.DrawImage(clone, 10, y) y += clone.Height + 10 e.Graphics.DrawString("center part of bitmap:", ArialFont, BlackBrush, 10, y) y += 20 e.Graphics.DrawImage(center, 10, y) y += center.Height + 10 ' Dispose graphic objects. arialFont.Dispose() blackBrush.Dispose() End Sub