Bitmap bmp = new Bitmap("example.jpg"); BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat); int bytesPerPixel = Bitmap.GetPixelFormatSize(bmp.PixelFormat) / 8; int totalBytes = Math.Abs(bmpData.Stride) * bmp.Height; byte[] pixelData = new byte[totalBytes]; Marshal.Copy(bmpData.Scan0, pixelData, 0, totalBytes); double totalIntensity = 0; for (int i = 0; i < pixelData.Length; i += bytesPerPixel) { int intensity = (int)pixelData[i] + (int)pixelData[i + 1] + (int)pixelData[i + 2]; totalIntensity += intensity; } double averageIntensity = totalIntensity / (bmp.Width * bmp.Height); bmp.UnlockBits(bmpData); Console.WriteLine("Average pixel intensity: " + averageIntensity);
Bitmap bmp = new Bitmap("example.jpg"); BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat); int bytesPerPixel = Bitmap.GetPixelFormatSize(bmp.PixelFormat) / 8; int totalBytes = Math.Abs(bmpData.Stride) * bmp.Height; byte[] pixelData = new byte[totalBytes]; Marshal.Copy(bmpData.Scan0, pixelData, 0, totalBytes); for (int y = 0; y < bmp.Height; y++) { for (int x = 0; x < bmp.Width; x++) { int offset = y * bmpData.Stride + x * bytesPerPixel; pixelData[offset + 2] = 255; // set red channel to max } } Marshal.Copy(pixelData, 0, bmpData.Scan0, totalBytes); bmp.UnlockBits(bmpData); using (Graphics g = Graphics.FromImage(bmp)) { Pen pen = new Pen(Color.Red, 3); g.DrawLine(pen, new Point(0, 0), new Point(bmp.Width, bmp.Height)); } bmp.Save("example_redline.jpg", ImageFormat.Jpeg);Package/Library: The LockImage method is part of the System.Drawing namespace in the System.Drawing.dll library.