Cómo: Copiar imágenes

Actualización: noviembre 2007

Aunque .NET Compact Framework no admite el método Image.Clone, es posible copiar imágenes completas o partes de ellas. Los ejemplos siguientes muestran cómo hacer lo siguiente:

  • Definir un método para crear un mapa de bits.

  • Definir un método sobrecargado para copiar un mapa de bits o parte de él.

  • Llamar a estos métodos y llevar las imágenes a la pantalla reemplazando el método OnPaint del formulario.

Para crear un mapa de bits

  • Este método crea un mapa de bits a efectos de demostración.
' 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
// Creates a bitmap for copying.
private Bitmap CreateBitmap(int sideSize)
{
    Bitmap bmp = new Bitmap(sideSize, sideSize);
    Graphics g = 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;
}

Para clonar un mapa de bits

  • La sobrecarga de este método toma un mapa de bits de origen como parámetro y devuelve el mapa de bits como copia.
' Copies the entire bitmap.
Overloads Function CopyBitmap(source As Bitmap) As Bitmap
    Return New Bitmap(source)
End Function
// Copies the entire bitmap.
protected Bitmap CopyBitmap(Bitmap source)
{
    return new Bitmap(source);
}

Para copiar parte de un mapa de bits

  • La sobrecarga de este método toma Rectangle como parámetro para determinar las dimensiones de la parte del mapa de bits que se va a devolver.
' Copies a part of the bitmap.
Overloads Function CopyBitmap(source As Bitmap, part As Rectangle) As Bitmap
    Dim bmp As New Bitmap(part.Width, part.Height)

    Dim g As Graphics = Graphics.FromImage(bmp)
    g.DrawImage(source, 0, 0, part, GraphicsUnit.Pixel)
    g.Dispose()

    Return bmp
End Function
// Copies a part of a bitmap.
protected Bitmap CopyBitmap(Bitmap source, Rectangle part)
{
    Bitmap bmp = new Bitmap(part.Width, part.Height);
    Graphics g = Graphics.FromImage(bmp);
    g.DrawImage(source,0,0,part,GraphicsUnit.Pixel);
    g.Dispose();
    return bmp;
}

Para crear, copiar y trazar los mapas de bits

  • La sobrecarga de este método OnPaint llama a los métodos para crear un mapa de bits y, a continuación, clonarlo y copiar una parte del mismo. Además, guarda en un archivo el mapa de bits clonado.
' 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
// Draws the bitmaps on the form.   
protected override void OnPaint(PaintEventArgs e)
{
    Font arialFont;
    Brush blackBrush;
    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.
    int sidesize = 75;
    int third = (int) sidesize/3;

    // Create bitmap.
    source = CreateBitmap(sidesize);

    // Copy entirely as a clone.
    clone = CopyBitmap(source);

    // Copy the center part of the bitmap.
    center = 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. 
    int y = 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();
}

Compilar el código

Para este ejemplo se requieren referencias a los siguientes espacios de nombres:

Programación eficaz

Tenga en cuenta que los objetos Font y Brush se eliminan explícitamente en la sobrecarga del método OnPaint. El recolector de elementos no utilizados destruye el objeto Graphics devuelto por la propiedad Graphics del objeto PaintEventArgs, por lo que no es necesario eliminarlo de manera explícita.

Vea también

Otros recursos

Gráficos y dibujos en .NET Compact Framework