Bitmap.LockBits Método

Definição

Bloqueia um Bitmap na memória do sistema.Locks a Bitmap into system memory.

Sobrecargas

LockBits(Rectangle, ImageLockMode, PixelFormat)

Bloqueia um Bitmap na memória do sistema.Locks a Bitmap into system memory.

LockBits(Rectangle, ImageLockMode, PixelFormat, BitmapData)

Bloqueia um Bitmap na memória do sistema.Locks a Bitmap into system memory.

LockBits(Rectangle, ImageLockMode, PixelFormat)

Bloqueia um Bitmap na memória do sistema.Locks a Bitmap into system memory.

public:
 System::Drawing::Imaging::BitmapData ^ LockBits(System::Drawing::Rectangle rect, System::Drawing::Imaging::ImageLockMode flags, System::Drawing::Imaging::PixelFormat format);
public System.Drawing.Imaging.BitmapData LockBits (System.Drawing.Rectangle rect, System.Drawing.Imaging.ImageLockMode flags, System.Drawing.Imaging.PixelFormat format);
member this.LockBits : System.Drawing.Rectangle * System.Drawing.Imaging.ImageLockMode * System.Drawing.Imaging.PixelFormat -> System.Drawing.Imaging.BitmapData
Public Function LockBits (rect As Rectangle, flags As ImageLockMode, format As PixelFormat) As BitmapData

Parâmetros

rect
Rectangle

Uma estrutura Rectangle que especifica a parte do Bitmap a ser bloqueada.A Rectangle structure that specifies the portion of the Bitmap to lock.

flags
ImageLockMode

Uma enumeração ImageLockMode que especifica o nível de acesso (leitura/gravação) do Bitmap.An ImageLockMode enumeration that specifies the access level (read/write) for the Bitmap.

format
PixelFormat

Uma enumeração PixelFormat que especifica o formato de dados deste Bitmap.A PixelFormat enumeration that specifies the data format of this Bitmap.

Retornos

BitmapData

Um BitmapData que contém informações sobre essa operação de bloqueio.A BitmapData that contains information about this lock operation.

Exceções

O PixelFormat não é um valor bits por pixel específico.The PixelFormat is not a specific bits-per-pixel value.

- ou --or- O PixelFormat incorreto é passado para um bitmap.The incorrect PixelFormat is passed in for a bitmap.

Falha na operação.The operation failed.

Exemplos

O exemplo de código a seguir demonstra como usar as PixelFormat Propriedades,, e Height Width Scan0 ; os LockBits UnlockBits métodos e; e a ImageLockMode enumeração.The following code example demonstrates how to use the PixelFormat, Height, Width, and Scan0 properties; the LockBits and UnlockBits methods; and the ImageLockMode enumeration. Este exemplo foi projetado para ser usado com Windows Forms.This example is designed to be used with Windows Forms. Este exemplo não foi projetado para funcionar corretamente com todos os formatos de pixel, mas para fornecer um exemplo de como usar o LockBits método.This example is not designed to work correctly with all pixel formats, but to provide an example of how to use the LockBits method. Para executar este exemplo, Cole-o em um formulário e manipule o evento do formulário Paint chamando o LockUnlockBitsExample método, passando e como PaintEventArgs .To run this example, paste it into a form and handle the form's Paint event by calling the LockUnlockBitsExample method, passing e as PaintEventArgs.

void LockUnlockBitsExample( PaintEventArgs^ e )
{
   // Create a new bitmap.
   Bitmap^ bmp = gcnew Bitmap( "c:\\fakePhoto.jpg" );

   // Lock the bitmap's bits.  
   Rectangle rect = Rectangle(0,0,bmp->Width,bmp->Height);
   System::Drawing::Imaging::BitmapData^ bmpData = bmp->LockBits( rect, System::Drawing::Imaging::ImageLockMode::ReadWrite, bmp->PixelFormat );

   // Get the address of the first line.
   IntPtr ptr = bmpData->Scan0;

   // Declare an array to hold the bytes of the bitmap.
   // This code is specific to a bitmap with 24 bits per pixels.
   int bytes = Math::Abs(bmpData->Stride) * bmp->Height;
   array<Byte>^rgbValues = gcnew array<Byte>(bytes);

   // Copy the RGB values into the array.
   System::Runtime::InteropServices::Marshal::Copy( ptr, rgbValues, 0, bytes );

   // Set every third value to 255.  
   for ( int counter = 2; counter < rgbValues->Length; counter += 3 )
      rgbValues[ counter ] = 255;

   // Copy the RGB values back to the bitmap
   System::Runtime::InteropServices::Marshal::Copy( rgbValues, 0, ptr, bytes );

   // Unlock the bits.
   bmp->UnlockBits( bmpData );

   // Draw the modified image.
   e->Graphics->DrawImage( bmp, 0, 150 );
}
private void LockUnlockBitsExample(PaintEventArgs e)
    {

        // Create a new bitmap.
        Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg");

        // Lock the bitmap's bits.  
        Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
        System.Drawing.Imaging.BitmapData bmpData =
            bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
            bmp.PixelFormat);

        // Get the address of the first line.
        IntPtr ptr = bmpData.Scan0;

        // Declare an array to hold the bytes of the bitmap.
        int bytes  = Math.Abs(bmpData.Stride) * bmp.Height;
        byte[] rgbValues = new byte[bytes];

        // Copy the RGB values into the array.
        System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

        // Set every third value to 255. A 24bpp bitmap will look red.  
        for (int counter = 2; counter < rgbValues.Length; counter += 3)
            rgbValues[counter] = 255;

        // Copy the RGB values back to the bitmap
        System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);

        // Unlock the bits.
        bmp.UnlockBits(bmpData);

        // Draw the modified image.
        e.Graphics.DrawImage(bmp, 0, 150);
    }

Private Sub LockUnlockBitsExample(ByVal e As PaintEventArgs)

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

    ' Lock the bitmap's bits.  
    Dim rect As New Rectangle(0, 0, bmp.Width, bmp.Height)
    Dim bmpData As System.Drawing.Imaging.BitmapData = bmp.LockBits(rect, _
        Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat)

    ' Get the address of the first line.
    Dim ptr As IntPtr = bmpData.Scan0

    ' Declare an array to hold the bytes of the bitmap.
    ' This code is specific to a bitmap with 24 bits per pixels.
    Dim bytes As Integer = Math.Abs(bmpData.Stride) * bmp.Height
    Dim rgbValues(bytes - 1) As Byte

    ' Copy the RGB values into the array.
    System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes)

    ' Set every third value to 255. A 24bpp image will look red.
    For counter As Integer = 2 To rgbValues.Length - 1 Step 3
        rgbValues(counter) = 255
    Next

    ' Copy the RGB values back to the bitmap
    System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes)

    ' Unlock the bits.
    bmp.UnlockBits(bmpData)

    ' Draw the modified image.
    e.Graphics.DrawImage(bmp, 0, 150)

End Sub

Comentários

Use o LockBits método para bloquear um bitmap existente na memória do sistema para que ele possa ser alterado programaticamente.Use the LockBits method to lock an existing bitmap in system memory so that it can be changed programmatically. Você pode alterar a cor de uma imagem com o SetPixel método, embora o LockBits método ofereça um melhor desempenho para alterações em larga escala.You can change the color of an image with the SetPixel method, although the LockBits method offers better performance for large-scale changes.

O BitmapData especifica os atributos do Bitmap , como tamanho, formato de pixel, o endereço inicial dos dados de pixel na memória e o comprimento de cada linha de exame (STRIDE).The BitmapData specifies the attributes of the Bitmap, such as size, pixel format, the starting address of the pixel data in memory, and length of each scan line (stride).

Ao chamar esse método, você deve usar um membro da System.Drawing.Imaging.PixelFormat enumeração que contém um valor específico de bits por pixel (BPP).When calling this method, you should use a member of the System.Drawing.Imaging.PixelFormat enumeration that contains a specific bits-per-pixel (BPP) value. Usar System.Drawing.Imaging.PixelFormat valores como e gerará Indexed Gdi um System.ArgumentException .Using System.Drawing.Imaging.PixelFormat values such as Indexed and Gdi will throw an System.ArgumentException. Além disso, passar o formato de pixel incorreto para um bitmap gerará um System.ArgumentException .Also, passing the incorrect pixel format for a bitmap will throw an System.ArgumentException.

Aplica-se a

LockBits(Rectangle, ImageLockMode, PixelFormat, BitmapData)

Bloqueia um Bitmap na memória do sistema.Locks a Bitmap into system memory.

public:
 System::Drawing::Imaging::BitmapData ^ LockBits(System::Drawing::Rectangle rect, System::Drawing::Imaging::ImageLockMode flags, System::Drawing::Imaging::PixelFormat format, System::Drawing::Imaging::BitmapData ^ bitmapData);
public System.Drawing.Imaging.BitmapData LockBits (System.Drawing.Rectangle rect, System.Drawing.Imaging.ImageLockMode flags, System.Drawing.Imaging.PixelFormat format, System.Drawing.Imaging.BitmapData bitmapData);
member this.LockBits : System.Drawing.Rectangle * System.Drawing.Imaging.ImageLockMode * System.Drawing.Imaging.PixelFormat * System.Drawing.Imaging.BitmapData -> System.Drawing.Imaging.BitmapData
Public Function LockBits (rect As Rectangle, flags As ImageLockMode, format As PixelFormat, bitmapData As BitmapData) As BitmapData

Parâmetros

rect
Rectangle

Uma estrutura em retângulo que especifica a parte do Bitmap a ser bloqueada.A rectangle structure that specifies the portion of the Bitmap to lock.

flags
ImageLockMode

Um dos valores ImageLockMode que especifica o nível de acesso (leitura/gravação) do Bitmap.One of the ImageLockMode values that specifies the access level (read/write) for the Bitmap.

format
PixelFormat

Um dos valores PixelFormat que especifica o formato de dados do Bitmap.One of the PixelFormat values that specifies the data format of the Bitmap.

bitmapData
BitmapData

Um BitmapData que contém informações sobre a operação de bloqueio.A BitmapData that contains information about the lock operation.

Retornos

BitmapData

Um BitmapData que contém informações sobre a operação de bloqueio.A BitmapData that contains information about the lock operation.

Exceções

O valor PixelFormat não é um valor bits por pixel específico.PixelFormat value is not a specific bits-per-pixel value.

- ou --or- O PixelFormat incorreto é passado para um bitmap.The incorrect PixelFormat is passed in for a bitmap.

Falha na operação.The operation failed.

Comentários

Use o LockBits método para bloquear um bitmap existente na memória do sistema para que ele possa ser alterado programaticamente.Use the LockBits method to lock an existing bitmap in system memory so that it can be changed programmatically. Você pode alterar a cor de uma imagem com o SetPixel método, embora o LockBits método ofereça um melhor desempenho para alterações em larga escala.You can change the color of an image with the SetPixel method, although the LockBits method offers better performance for large-scale changes.

Ao chamar esse método, você deve usar um membro da System.Drawing.Imaging.PixelFormat enumeração que contém um valor específico de bits por pixel (BPP).When calling this method, you should use a member of the System.Drawing.Imaging.PixelFormat enumeration that contains a specific bits-per-pixel (BPP) value. O uso de System.Drawing.Imaging.PixelFormat valores, como Indexed e Gdi , gerará um System.ArgumentException .Using System.Drawing.Imaging.PixelFormat values, such as Indexed and Gdi, will throw an System.ArgumentException. Além disso, passar o formato de pixel incorreto para um bitmap gerará um System.ArgumentException .Also, passing the incorrect pixel format for a bitmap will throw an System.ArgumentException.

Esta versão do LockBits método destina-se a ser usada com um flags valor de ImageLockMode.UserInputBuffer .This version of the LockBits method is intended to be used with a flags value of ImageLockMode.UserInputBuffer.

Aplica-se a