/// <summary> /// Begin editing an image. /// </summary> public static byte[] Begin(Bitmap bitmap, ImageLockMode lockMode, out BitmapData bmpData) { // Lock full image Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); // Lock the bitmap's bits while we change them. bmpData = bitmap.LockBits(rect, lockMode, bitmap.PixelFormat); // Create length with number of bytes in image byte[] rgbValues = new byte[bmpData.GetByteCount()]; // Copy the RGB values into the array. Marshal.Copy(bmpData.Scan0, rgbValues, 0, rgbValues.Length); // Check if monochrome if (bitmap.PixelFormat == PixelFormat.Format1bppIndexed) { // Adjust stride bmpData.Stride *= Constants.BitsPerByte; // Convert each bit to a separate byte return(ImageBytes.BytesToBits(rgbValues)); } else { return(rgbValues); } }
/// <summary> /// Gets the bytes from a bitmap image (image portion only). /// </summary> /// <param name="bitmap">Bitmap to get bytes from</param> /// <param name="bmpData">Data relating to bitmap</param> /// <returns>Image bytes</returns> private static byte[] GetBitmapBytes(Bitmap bitmap, out BitmapData bmpData) { // Lock full image Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); // Lock the bits while we read them. bmpData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat); // Create length with number of bytes in image byte[] rgbValues = new byte[bmpData.GetByteCount()]; // Copy the RGB values into the array. Marshal.Copy(bmpData.Scan0, rgbValues, 0, rgbValues.Length); // Check if monochrome if (bitmap.PixelFormat == PixelFormat.Format1bppIndexed) { // Adjust stride bmpData.Stride *= Constants.BitsPerByte; // Convert each bit to a separate byte rgbValues = BytesToBits(rgbValues).Select(b => b > 0 ? byte.MaxValue : byte.MinValue).ToArray(); } // Unlock the bits. bitmap.UnlockBits(bmpData); return(rgbValues); }