// Load an image file BitmapImage image = new BitmapImage(new Uri("image.jpg", UriKind.Relative)); // Create a BitmapSource from the image BitmapSource bitmapSource = new FormatConvertedBitmap(image, PixelFormats.Bgra32, null, 0); // Define the size of the buffer to copy the pixel data to int stride = bitmapSource.PixelWidth * 4; int size = bitmapSource.PixelHeight * stride; byte[] buffer = new byte[size]; // Copy the pixel data to the buffer bitmapSource.CopyPixels(buffer, stride, 0); // Display the pixel data for (int i = 0; i < size; i += 4) { byte blue = buffer[i]; byte green = buffer[i + 1]; byte red = buffer[i + 2]; byte alpha = buffer[i + 3]; Console.WriteLine($"Pixel at {i / 4}: R={red}, G={green}, B={blue}, A={alpha}"); }
// Create a new BitmapSource BitmapSource bitmapSource = BitmapSource.Create(100, 100, 96, 96, PixelFormats.Bgra32, null, new byte[40000], 400); // Copy the pixel data to a new buffer byte[] buffer = new byte[40000]; bitmapSource.CopyPixels(buffer, 400, 0); // Modify the pixel data for (int i = 0; i < 40000; i += 4) { buffer[i] = 255; // Blue buffer[i + 1] = 0; // Green buffer[i + 2] = 0; // Red buffer[i + 3] = 255; // Alpha } // Copy the modified pixel data back to the BitmapSource bitmapSource.CopyPixels(buffer, 400, 0); // Display the modified BitmapSource Image image = new Image(); image.Source = bitmapSource;This example creates a new BitmapSource, copies its pixel data to a buffer, modifies the buffer to set all pixels to blue, and then copies the modified pixel data back to the BitmapSource. Finally, the modified BitmapSource is displayed in an Image control. These examples have been written using the C# programming language and the System.Windows.Media.Imaging namespace, which is part of the .NET Framework.