Bitmap Constructores

Definición

Inicializa una nueva instancia de la clase Bitmap.

Sobrecargas

Bitmap(Image)

Inicializa una nueva instancia de la clase Bitmap a partir de la imagen especificada existente.

Bitmap(Stream)

Inicializa una nueva instancia de la clase Bitmap a partir del flujo de datos especificado.

Bitmap(String)

Inicializa una nueva instancia de la clase Bitmap a partir del archivo especificado.

Bitmap(Image, Size)

Inicializa una nueva instancia de la clase Bitmap a partir de la imagen existente especificada, escalada al tamaño especificado.

Bitmap(Int32, Int32)

Inicializa una nueva instancia de la clase Bitmap con el tamaño especificado.

Bitmap(Stream, Boolean)

Inicializa una nueva instancia de la clase Bitmap a partir del flujo de datos especificado.

Bitmap(String, Boolean)

Inicializa una nueva instancia de la clase Bitmap a partir del archivo especificado.

Bitmap(Type, String)

Inicializa una nueva instancia de la clase Bitmap a partir de un recurso especificado.

Bitmap(Image, Int32, Int32)

Inicializa una nueva instancia de la clase Bitmap a partir de la imagen existente especificada, escalada al tamaño especificado.

Bitmap(Int32, Int32, Graphics)

Inicializa una nueva instancia de la clase Bitmap con el tamaño especificado y la resolución del objeto Graphics especificado.

Bitmap(Int32, Int32, PixelFormat)

Inicializa una nueva instancia de la clase Bitmap con el tamaño y el formato especificados.

Bitmap(Int32, Int32, Int32, PixelFormat, IntPtr)

Inicializa una nueva instancia de la clase Bitmap con el tamaño, el formato de píxel y los datos de píxel especificados.

Bitmap(Image)

Source:
Bitmap.cs
Source:
Bitmap.cs
Source:
Bitmap.cs

Inicializa una nueva instancia de la clase Bitmap a partir de la imagen especificada existente.

public:
 Bitmap(System::Drawing::Image ^ original);
public Bitmap (System.Drawing.Image original);
new System.Drawing.Bitmap : System.Drawing.Image -> System.Drawing.Bitmap
Public Sub New (original As Image)

Parámetros

original
Image

Objeto Image a partir del cual se creará el nuevo objeto Bitmap.

Se aplica a

Bitmap(Stream)

Source:
Bitmap.cs
Source:
Bitmap.cs
Source:
Bitmap.cs

Inicializa una nueva instancia de la clase Bitmap a partir del flujo de datos especificado.

public:
 Bitmap(System::IO::Stream ^ stream);
public Bitmap (System.IO.Stream stream);
new System.Drawing.Bitmap : System.IO.Stream -> System.Drawing.Bitmap
Public Sub New (stream As Stream)

Parámetros

stream
Stream

El flujo de datos que se usa para cargar la imagen.

Excepciones

stream no contiene datos de imagen o es null.

o bien

stream contiene un archivo de imagen PNG con una única dimensión superior a 65 535 píxeles.

Ejemplos

En el ejemplo de código siguiente se muestra cómo cargar un mapa de bits desde una secuencia.

Este ejemplo está diseñado para usarse con Windows Forms. Cree un formulario que contenga un PictureBox objeto denominado PictureBox1. Pegue el código en el formulario y llame al InitializeStreamBitmap método desde el constructor o Load el método de control de eventos del formulario.

void InitializeStreamBitmap()
{
   try
   {
      System::Net::WebRequest^ request = System::Net::WebRequest::Create( "http://www.microsoft.com//h/en-us/r/ms_masthead_ltr.gif" );
      System::Net::WebResponse^ response = request->GetResponse();
      System::IO::Stream^ responseStream = response->GetResponseStream();
      Bitmap^ bitmap2 = gcnew Bitmap( responseStream );
      PictureBox1->Image = bitmap2;
   }
   catch ( System::Net::WebException^ ) 
   {
      MessageBox::Show( "There was an error opening the image file."
      "Check the URL" );
   }

}
private void InitializeStreamBitmap()
{
    try
    {
        System.Net.WebRequest request = 
            System.Net.WebRequest.Create(
            "http://www.microsoft.com//h/en-us/r/ms_masthead_ltr.gif");
        System.Net.WebResponse response = request.GetResponse();
        System.IO.Stream responseStream = 
            response.GetResponseStream();
        Bitmap bitmap2 = new Bitmap(responseStream);
        PictureBox1.Image = bitmap2;
    }
    catch(System.Net.WebException)
    {
        MessageBox.Show("There was an error opening the image file."
           + "Check the URL");
    }
}
Private Sub InitializeStreamBitmap()
    Try
        Dim request As System.Net.WebRequest = _
            System.Net.WebRequest.Create( _
            "http://www.microsoft.com//h/en-us/r/ms_masthead_ltr.gif")
        Dim response As System.Net.WebResponse = request.GetResponse()
        Dim responseStream As System.IO.Stream = response.GetResponseStream()
        Dim bitmap2 As New Bitmap(responseStream)
        PictureBox1.Image = bitmap2

    Catch ex As System.Net.WebException
        MessageBox.Show("There was an error opening the image file. Check the URL")
    End Try
End Sub

Comentarios

Debe mantener abierta la secuencia durante la vigencia de Bitmap.

Debido a una limitación del descodificador GDI+, se produce una System.ArgumentException excepción si crea un mapa de bits a partir de un archivo de imagen de .png con una sola dimensión superior a 65 535 píxeles.

Consulte también

Se aplica a

Bitmap(String)

Source:
Bitmap.cs
Source:
Bitmap.cs
Source:
Bitmap.cs

Inicializa una nueva instancia de la clase Bitmap a partir del archivo especificado.

public:
 Bitmap(System::String ^ filename);
public Bitmap (string filename);
new System.Drawing.Bitmap : string -> System.Drawing.Bitmap
Public Sub New (filename As String)

Parámetros

filename
String

Nombre y ruta de acceso al archivo de mapa de bits.

Excepciones

No se encontró el archivo especificado.

Comentarios

El nombre de archivo y la ruta de acceso pueden ser relativos a la aplicación o a una ruta de acceso absoluta. Use este constructor para abrir imágenes con los siguientes formatos de archivo: BMP, GIF, EXIF, JPG, PNG y TIFF. Para obtener más información sobre los formatos admitidos, vea Tipos de mapas de bits. El archivo permanece bloqueado hasta Bitmap que se elimina .

Consulte también

Se aplica a

Bitmap(Image, Size)

Source:
Bitmap.cs
Source:
Bitmap.cs
Source:
Bitmap.cs

Inicializa una nueva instancia de la clase Bitmap a partir de la imagen existente especificada, escalada al tamaño especificado.

public:
 Bitmap(System::Drawing::Image ^ original, System::Drawing::Size newSize);
public Bitmap (System.Drawing.Image original, System.Drawing.Size newSize);
new System.Drawing.Bitmap : System.Drawing.Image * System.Drawing.Size -> System.Drawing.Bitmap
Public Sub New (original As Image, newSize As Size)

Parámetros

original
Image

Objeto Image a partir del cual se creará el nuevo objeto Bitmap.

newSize
Size

Estructura Size que representa el tamaño de la nueva clase Bitmap.

Excepciones

Error en la operación.

Se aplica a

Bitmap(Int32, Int32)

Source:
Bitmap.cs
Source:
Bitmap.cs
Source:
Bitmap.cs

Inicializa una nueva instancia de la clase Bitmap con el tamaño especificado.

public:
 Bitmap(int width, int height);
public Bitmap (int width, int height);
new System.Drawing.Bitmap : int * int -> System.Drawing.Bitmap
Public Sub New (width As Integer, height As Integer)

Parámetros

width
Int32

Ancho (en píxeles) del nuevo Bitmap.

height
Int32

Alto (en píxeles) del nuevo Bitmap.

Excepciones

Error en la operación.

Comentarios

Este constructor crea un Bitmap objeto con un PixelFormat valor de enumeración de Format32bppArgb.

Se aplica a

Bitmap(Stream, Boolean)

Source:
Bitmap.cs
Source:
Bitmap.cs
Source:
Bitmap.cs

Inicializa una nueva instancia de la clase Bitmap a partir del flujo de datos especificado.

public:
 Bitmap(System::IO::Stream ^ stream, bool useIcm);
public Bitmap (System.IO.Stream stream, bool useIcm);
new System.Drawing.Bitmap : System.IO.Stream * bool -> System.Drawing.Bitmap
Public Sub New (stream As Stream, useIcm As Boolean)

Parámetros

stream
Stream

El flujo de datos que se usa para cargar la imagen.

useIcm
Boolean

true para aplicar la corrección de color en este objeto Bitmap; de lo contrario, false.

Excepciones

stream no contiene datos de imagen o es null.

o bien

stream contiene un archivo de imagen PNG con una única dimensión superior a 65 535 píxeles.

Comentarios

Debe mantener abierta la secuencia durante la vigencia de Bitmap.

Debido a una limitación del descodificador GDI+, se produce una System.ArgumentException excepción si crea un mapa de bits a partir de un archivo de imagen de .png con una sola dimensión superior a 65 535 píxeles.

Consulte también

Se aplica a

Bitmap(String, Boolean)

Source:
Bitmap.cs
Source:
Bitmap.cs
Source:
Bitmap.cs

Inicializa una nueva instancia de la clase Bitmap a partir del archivo especificado.

public:
 Bitmap(System::String ^ filename, bool useIcm);
public Bitmap (string filename, bool useIcm);
new System.Drawing.Bitmap : string * bool -> System.Drawing.Bitmap
Public Sub New (filename As String, useIcm As Boolean)

Parámetros

filename
String

Nombre del archivo de mapa de bits.

useIcm
Boolean

true para aplicar la corrección de color en este objeto Bitmap; de lo contrario, false.

Ejemplos

En el ejemplo de código siguiente se muestra cómo construir un nuevo mapa de bits a partir de un archivo. En el ejemplo se usan los GetPixel métodos y SetPixel para volver a colorear la imagen. También usa la PixelFormat propiedad .

Este ejemplo está diseñado para usarse con un formulario Windows Forms que contiene , LabelPictureBox y Button denominado Label1, PictureBox1 y Button1, respectivamente. Pegue el código en el formulario y asocie el Button1_Click método al evento del Click botón.

private:
   Bitmap^ image1;
   void Button1_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      try
      {
         
         // Retrieve the image.
         image1 = gcnew Bitmap( "C:\\Documents and Settings\\All Users\\"
         "Documents\\My Music\\music.bmp",true );
         int x;
         int y;
         
         // Loop through the images pixels to reset color.
         for ( x = 0; x < image1->Width; x++ )
         {
            for ( y = 0; y < image1->Height; y++ )
            {
               Color pixelColor = image1->GetPixel( x, y );
               Color newColor = Color::FromArgb( pixelColor.R, 0, 0 );
               image1->SetPixel( x, y, newColor );

            }

         }
         
         // Set the PictureBox to display the image.
         PictureBox1->Image = image1;
         
         // Display the pixel format in Label1.
         Label1->Text = String::Format( "Pixel format: {0}", image1->PixelFormat );
      }
      catch ( ArgumentException^ ) 
      {
         MessageBox::Show( "There was an error."
         "Check the path to the image file." );
      }

   }
Bitmap image1;

private void Button1_Click(System.Object sender, System.EventArgs e)
{

    try
    {
        // Retrieve the image.
        image1 = new Bitmap(@"C:\Documents and Settings\All Users\" 
            + @"Documents\My Music\music.bmp", true);

        int x, y;

        // Loop through the images pixels to reset color.
        for(x=0; x<image1.Width; x++)
        {
            for(y=0; y<image1.Height; y++)
            {
                Color pixelColor = image1.GetPixel(x, y);
                Color newColor = Color.FromArgb(pixelColor.R, 0, 0);
                image1.SetPixel(x, y, newColor);
            }
        }

        // Set the PictureBox to display the image.
        PictureBox1.Image = image1;

        // Display the pixel format in Label1.
        Label1.Text = "Pixel format: "+image1.PixelFormat.ToString();
    }
    catch(ArgumentException)
    {
        MessageBox.Show("There was an error." +
            "Check the path to the image file.");
    }
}
Dim image1 As Bitmap

Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click

    Try
        ' Retrieve the image.
        image1 = New Bitmap( _
            "C:\Documents and Settings\All Users\Documents\My Music\music.bmp", _
            True)

        Dim x, y As Integer

        ' Loop through the images pixels to reset color.
        For x = 0 To image1.Width - 1
            For y = 0 To image1.Height - 1
                Dim pixelColor As Color = image1.GetPixel(x, y)
                Dim newColor As Color = _
                    Color.FromArgb(pixelColor.R, 0, 0)
                image1.SetPixel(x, y, newColor)
            Next
        Next

        ' Set the PictureBox to display the image.
        PictureBox1.Image = image1

        ' Display the pixel format in Label1.
        Label1.Text = "Pixel format: " + image1.PixelFormat.ToString()

    Catch ex As ArgumentException
        MessageBox.Show("There was an error." _
            & "Check the path to the image file.")
    End Try
End Sub

Comentarios

Use este constructor para abrir imágenes con los siguientes formatos de archivo: BMP, GIF, EXIF, JPG, PNG y TIFF. Para obtener más información sobre los formatos admitidos, vea Tipos de mapas de bits. El archivo permanece bloqueado hasta Bitmap que se elimina .

Consulte también

Se aplica a

Bitmap(Type, String)

Source:
Bitmap.cs
Source:
Bitmap.cs
Source:
Bitmap.cs

Inicializa una nueva instancia de la clase Bitmap a partir de un recurso especificado.

public:
 Bitmap(Type ^ type, System::String ^ resource);
public Bitmap (Type type, string resource);
new System.Drawing.Bitmap : Type * string -> System.Drawing.Bitmap
Public Sub New (type As Type, resource As String)

Parámetros

type
Type

Clase utilizada para extraer el recurso.

resource
String

Nombre del recurso.

Ejemplos

En el ejemplo de código siguiente se muestra cómo construir un mapa de bits a partir de un tipo y cómo usar el Save método . Para ejecutar este ejemplo, pegue el código en un formulario Windows Forms. Controle el evento del Paint formulario y llame al ConstructFromResourceSaveAsGif método , pasando e como PaintEventArgs

private:
    void ConstructFromResourceSaveAsGif(PaintEventArgs^ e)
    {
        // Construct a bitmap from the button image resource.
        Bitmap^ bmp1 = gcnew Bitmap(Button::typeid, "Button.bmp");
        String^ savePath =  
            Environment::GetEnvironmentVariable("TEMP") + "\\Button.bmp";

        try
        {
            // Save the image as a GIF.
            bmp1->Save(savePath, System::Drawing::Imaging::ImageFormat::Gif);
        }
        catch (IOException^)
        {
            // Carry on regardless
        }

        // Construct a new image from the GIF file.
        Bitmap^ bmp2 = nullptr;
        if (File::Exists(savePath))
        {
            bmp2 = gcnew Bitmap(savePath);
        }

        // Draw the two images.
        e->Graphics->DrawImage(bmp1, Point(10, 10));

        // If bmp1 did not save to disk, bmp2 may be null
        if (bmp2 != nullptr)
        {
            e->Graphics->DrawImage(bmp2, Point(10, 40));
        }

        // Dispose of the image files.
        delete bmp1;
        if (bmp2 != nullptr)
        {
            delete bmp2;
        }
    }
private void ConstructFromResourceSaveAsGif(PaintEventArgs e)
{

    // Construct a bitmap from the button image resource.
    Bitmap bmp1 = new Bitmap(typeof(Button), "Button.bmp");

    // Save the image as a GIF.
    bmp1.Save("c:\\button.gif", System.Drawing.Imaging.ImageFormat.Gif);

    // Construct a new image from the GIF file.
    Bitmap bmp2 = new Bitmap("c:\\button.gif");

    // Draw the two images.
    e.Graphics.DrawImage(bmp1, new Point(10, 10));
    e.Graphics.DrawImage(bmp2, new Point(10, 40));

    // Dispose of the image files.
    bmp1.Dispose();
    bmp2.Dispose();
}
Private Sub ConstructFromResourceSaveAsGif(ByVal e As PaintEventArgs)

    ' Construct a bitmap from the button image resource.
    Dim bmp1 As New Bitmap(GetType(Button), "Button.bmp")

    ' Save the image as a GIF.
    bmp1.Save("c:\button.gif", System.Drawing.Imaging.ImageFormat.Gif)

    ' Construct a new image from the GIF file.
    Dim bmp2 As New Bitmap("c:\button.gif")

    ' Draw the two images.
    e.Graphics.DrawImage(bmp1, New Point(10, 10))
    e.Graphics.DrawImage(bmp2, New Point(10, 40))

    ' Dispose of the image files.
    bmp1.Dispose()
    bmp2.Dispose()
End Sub

Comentarios

Este constructor combina el espacio de nombres del tipo especificado con el nombre de cadena del recurso y busca una coincidencia en el manifiesto del ensamblado. Por ejemplo, puede pasar el Button tipo y Button.bmp a este constructor y buscará un recurso denominado System.Windows.Forms.Button.bmp.

Consulte también

Se aplica a

Bitmap(Image, Int32, Int32)

Source:
Bitmap.cs
Source:
Bitmap.cs
Source:
Bitmap.cs

Inicializa una nueva instancia de la clase Bitmap a partir de la imagen existente especificada, escalada al tamaño especificado.

public:
 Bitmap(System::Drawing::Image ^ original, int width, int height);
public Bitmap (System.Drawing.Image original, int width, int height);
new System.Drawing.Bitmap : System.Drawing.Image * int * int -> System.Drawing.Bitmap
Public Sub New (original As Image, width As Integer, height As Integer)

Parámetros

original
Image

Objeto Image a partir del cual se creará el nuevo objeto Bitmap.

width
Int32

Ancho (en píxeles) del nuevo Bitmap.

height
Int32

Alto (en píxeles) del nuevo Bitmap.

Excepciones

Error en la operación.

Se aplica a

Bitmap(Int32, Int32, Graphics)

Source:
Bitmap.cs
Source:
Bitmap.cs
Source:
Bitmap.cs

Inicializa una nueva instancia de la clase Bitmap con el tamaño especificado y la resolución del objeto Graphics especificado.

public:
 Bitmap(int width, int height, System::Drawing::Graphics ^ g);
public Bitmap (int width, int height, System.Drawing.Graphics g);
new System.Drawing.Bitmap : int * int * System.Drawing.Graphics -> System.Drawing.Bitmap
Public Sub New (width As Integer, height As Integer, g As Graphics)

Parámetros

width
Int32

Ancho (en píxeles) del nuevo Bitmap.

height
Int32

Alto (en píxeles) del nuevo Bitmap.

g
Graphics

Objeto Graphics que especifica la resolución de la nueva clase Bitmap.

Excepciones

Comentarios

El nuevo Bitmap objeto que crea este método toma su resolución horizontal y vertical de las DpiX propiedades y DpiY de g, respectivamente.

Se aplica a

Bitmap(Int32, Int32, PixelFormat)

Source:
Bitmap.cs
Source:
Bitmap.cs
Source:
Bitmap.cs

Inicializa una nueva instancia de la clase Bitmap con el tamaño y el formato especificados.

public:
 Bitmap(int width, int height, System::Drawing::Imaging::PixelFormat format);
public Bitmap (int width, int height, System.Drawing.Imaging.PixelFormat format);
new System.Drawing.Bitmap : int * int * System.Drawing.Imaging.PixelFormat -> System.Drawing.Bitmap
Public Sub New (width As Integer, height As Integer, format As PixelFormat)

Parámetros

width
Int32

Ancho (en píxeles) del nuevo Bitmap.

height
Int32

Alto (en píxeles) del nuevo Bitmap.

format
PixelFormat

El formato de píxeles para el nuevo Bitmap. Debe especificar un valor que comience por Format.

Excepciones

Se especifica un valor PixelFormat cuyo nombre no empieza por Format. Por ejemplo, especificar Gdi producirá un ArgumentException, pero Format48bppRgb no.

Se aplica a

Bitmap(Int32, Int32, Int32, PixelFormat, IntPtr)

Source:
Bitmap.cs
Source:
Bitmap.cs
Source:
Bitmap.cs

Inicializa una nueva instancia de la clase Bitmap con el tamaño, el formato de píxel y los datos de píxel especificados.

public:
 Bitmap(int width, int height, int stride, System::Drawing::Imaging::PixelFormat format, IntPtr scan0);
public Bitmap (int width, int height, int stride, System.Drawing.Imaging.PixelFormat format, IntPtr scan0);
new System.Drawing.Bitmap : int * int * int * System.Drawing.Imaging.PixelFormat * nativeint -> System.Drawing.Bitmap
Public Sub New (width As Integer, height As Integer, stride As Integer, format As PixelFormat, scan0 As IntPtr)

Parámetros

width
Int32

Ancho (en píxeles) del nuevo Bitmap.

height
Int32

Alto (en píxeles) del nuevo Bitmap.

stride
Int32

Entero que especifica el desplazamiento de bytes entre el principio de una línea de exploración y la siguiente. Normalmente (aunque no necesariamente) es el número de bytes del formato de píxel (por ejemplo, 2 por 16 bits por píxel) multiplicado por el ancho del mapa de bits. El valor que se pase a este parámetro tiene que ser múltiplo de cuatro.

format
PixelFormat

El formato de píxeles para el nuevo Bitmap. Debe especificar un valor que comience por Format.

scan0
IntPtr

nativeint

Puntero a una matriz de bytes que contiene los datos de píxeles.

Excepciones

Se especifica un valor PixelFormat cuyo nombre no empieza por Format. Por ejemplo, especificar Gdi producirá un ArgumentException, pero Format48bppRgb no.

Ejemplos

En el ejemplo de código siguiente se muestra cómo usar el Bitmap(Int32, Int32, Int32, PixelFormat, IntPtr) constructor . Este ejemplo está diseñado para usarse con Windows Forms y requiere un PaintEventArgs parámetro , que es un parámetro del Paint evento.

private void BitmapConstructorEx(PaintEventArgs e)
{

    // Create a bitmap.
    Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg");
    
   // Retrieve the bitmap data from the bitmap.
    System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), 
        ImageLockMode.ReadOnly, bmp.PixelFormat);

    //Create a new bitmap.
    Bitmap newBitmap = new Bitmap(200, 200, bmpData.Stride, bmp.PixelFormat, bmpData.Scan0);

    bmp.UnlockBits(bmpData);

    // Draw the new bitmap.
    e.Graphics.DrawImage(newBitmap, 10, 10);
}
Private Sub BitmapConstructorEx(ByVal e As PaintEventArgs)

    ' Create a bitmap.
    Dim bmp As New Bitmap("c:\fakePhoto.jpg")

    ' Retrieve the bitmap data from the bitmap.
    Dim bmpData As System.Drawing.Imaging.BitmapData = bmp.LockBits(New Rectangle(0, 0, bmp.Width, bmp.Height), _
        ImageLockMode.ReadOnly, bmp.PixelFormat)

    'Create a new bitmap.
    Dim newBitmap As New Bitmap(200, 200, bmpData.Stride, bmp.PixelFormat, bmpData.Scan0)

    bmp.UnlockBits(bmpData)

    ' Draw the new bitmap.
    e.Graphics.DrawImage(newBitmap, 10, 10)

End Sub

Comentarios

El autor de la llamada es responsable de asignar y liberar el bloque de memoria especificado por el scan0 parámetro . Sin embargo, la memoria no debe liberarse hasta que se libere la relación Bitmap .

Se aplica a