Advertisement
Guest User

Bitmap LockBits Example

a guest
Sep 7th, 2014
1,067
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.81 KB | None | 0 0
  1.  byte[] rgbValues;
  2.  private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
  3.         {
  4.             paintWind.Image = Bitmap.FromFile(openFileDialog1.FileName);
  5.             g = Graphics.FromImage(paintWind.Image);
  6.             Bitmap bmp = paintWind.Image as Bitmap;
  7.  
  8.             // Lock the bitmap's bits.  
  9.             Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
  10.             System.Drawing.Imaging.BitmapData bmpData =
  11.                 bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
  12.                 bmp.PixelFormat);
  13.  
  14.             // Get the address of the first line.
  15.             IntPtr ptr = bmpData.Scan0;
  16.  
  17.             // Declare an array to hold the bytes of the bitmap.
  18.             int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
  19.             rgbValues = new byte[bytes];
  20.  
  21.             // Copy the RGB values into the array.
  22.             System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
  23.  
  24.             // Set every third value to 255. A 24bpp bitmap will look red.  
  25.             for (int counter = 0; counter < rgbValues.Length; counter+=3)
  26.             {                
  27.                 //rgbValues[counter+1] = 255;                                
  28.             }
  29.             // Copy the RGB values back to the bitmap
  30.             System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
  31.  
  32.             // Unlock the bits.
  33.             bmp.UnlockBits(bmpData);
  34.  
  35.             int i = 0;
  36.             for (int counter = 0; counter < rgbValues.Length; counter += 3)
  37.             {
  38.                 bmp.SetPixel(i % bmp.Width, i / bmp.Width,
  39.                     Color.FromArgb(rgbValues[counter], rgbValues[counter + 1], rgbValues[counter + 2]));
  40.                 i++;
  41.  
  42.             }
  43.             paintWind.Refresh();
  44.            
  45.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement