Bitmap.LockBits Método

Definição

Bloqueia a Bitmap na memória do sistema.

Sobrecargas

Name Description
LockBits(Rectangle, ImageLockMode, PixelFormat)

Bloqueia a Bitmap na memória do sistema.

LockBits(Rectangle, ImageLockMode, PixelFormat, BitmapData)

Bloqueia a Bitmap na memória do sistema.

LockBits(Rectangle, ImageLockMode, PixelFormat)

Bloqueia a Bitmap na memória do sistema.

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 Rectangle estrutura que especifica a porção do Bitmap para bloquear.

flags
ImageLockMode

Uma ImageLockMode enumeração que especifica o nível de acesso (leitura/escrita) para o Bitmap.

format
PixelFormat

Uma PixelFormat enumeração que especifica o formato de dados deste Bitmap.

Devoluções

A que contém informação sobre esta operação de BitmapData bloqueio.

Exceções

Não PixelFormat é um valor específico de bits por píxel.

-ou-

O incorreto PixelFormat é entregue para um bitmap.

A operação falhou.

Exemplos

O seguinte exemplo de código demonstra como usar os PixelFormatmétodos , Height, Width, e Scan0 as propriedades; os LockBits métodos e UnlockBits ; e a ImageLockMode enumeração. Este exemplo foi concebido para ser usado com Windows Forms. Este exemplo não foi concebido para funcionar corretamente com todos os formatos de pixel, mas sim para fornecer um exemplo de como usar o LockBits método. Para executar este exemplo, colo-o num formulário e trate do evento do Paint formulário chamando o LockUnlockBitsExample método, passando e como 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

Observações

Use o LockBits método para bloquear um bitmap existente na memória do sistema para que possa ser alterado programaticamente. Pode alterar a cor de uma imagem com o SetPixel método, embora este LockBits ofereça melhor desempenho para alterações em grande escala.

Especifica BitmapData os atributos do Bitmap, como tamanho, formato de píxel, o endereço inicial dos dados do pixel na memória e o comprimento de cada linha de varrimento (stride).

Ao chamar este método, deve usar um membro da System.Drawing.Imaging.PixelFormat enumeração que contenha um valor específico de bits por píxel (BPP). Usar System.Drawing.Imaging.PixelFormat valores como Indexed e Gdi irá lançar um System.ArgumentException. Além disso, passar o formato de píxel incorreto para um bitmap gera um System.ArgumentExceptionformato .

Aplica-se a

LockBits(Rectangle, ImageLockMode, PixelFormat, BitmapData)

Bloqueia a Bitmap na memória do sistema.

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 retangular que especifica a parte do Bitmap a bloquear.

flags
ImageLockMode

Um dos ImageLockMode valores que especifica o nível de acesso (leitura/escrita) para o Bitmap.

format
PixelFormat

Um dos PixelFormat valores que especifica o formato de dados do Bitmap.

bitmapData
BitmapData

A que contém informação sobre a operação do BitmapData bloqueio.

Devoluções

A que contém informação sobre a operação do BitmapData bloqueio.

Exceções

PixelFormat o valor não é um valor específico de bits por píxel.

-ou-

O incorreto PixelFormat é entregue para um bitmap.

A operação falhou.

Observações

Use o LockBits método para bloquear um bitmap existente na memória do sistema para que possa ser alterado programaticamente. Pode alterar a cor de uma imagem com o SetPixel método, embora este LockBits ofereça melhor desempenho para alterações em grande escala.

Ao chamar este método, deve usar um membro da System.Drawing.Imaging.PixelFormat enumeração que contenha um valor específico de bits por píxel (BPP). Usar System.Drawing.Imaging.PixelFormat valores, como Indexed e Gdi, gerará um System.ArgumentException. Além disso, passar o formato de píxel incorreto para um bitmap gera um System.ArgumentExceptionformato .

Esta versão do LockBits método destina-se a ser usada com um flags valor de ImageLockMode.UserInputBuffer.

Aplica-se a