C# Image Examples
C# Basic
C# Data Type
C# OOP
C# IO
C# Graphics & UI
C# Advanced
To convert a Bitmap image into a byte array in C#, you can use the following code:
public byte[] ImageToByteArray(Bitmap image) { using (var stream = new MemoryStream()) { image.Save(stream, ImageFormat.Png); return stream.ToArray(); } }
To create a Bitmap from a byte array of pixel data in C#, you can use the following code:
public Bitmap ByteArrayToImage(byte[] byteArray) { using (var stream = new MemoryStream(byteArray)) { return new Bitmap(stream); } }
To compare two images using byte arrays in C#, you can use the following code:
public bool CompareImages(byte[] byteArray1, byte[] byteArray2) { if (byteArray1.Length != byteArray2.Length) { return false; } for (int i = 0; i < byteArray1.Length; i++) { if (byteArray1[i] != byteArray2[i]) { return false; } } return true; }
Note that in the above code, the CompareImages
method compares the two byte arrays directly. This is a very basic form of comparison and may not be suitable for more complex image comparison scenarios.
Load image in C#:
using (var image = Image.FromFile("path/to/image.jpg")) { // Work with the loaded image }
Drawing images in C#:
using (var graphics = Graphics.FromImage(destinationImage)) { graphics.DrawImage(sourceImage, new Point(0, 0)); }
Image resizing in C#:
using (var resizedImage = new Bitmap(originalImage, new Size(newWidth, newHeight))) { // Work with the resized image }
Working with pixel data in C#:
Color pixelColor = bitmap.GetPixel(x, y);
Creating images in C#:
using (var newImage = new Bitmap(width, height)) { // Work with the newly created image }
Image format conversion in C#:
using (var originalImage = Image.FromFile("original.png")) { originalImage.Save("converted.jpg", ImageFormat.Jpeg); }
C# image cropping:
using (var croppedImage = new Bitmap(originalImage.Clone(new Rectangle(x, y, width, height), originalImage.PixelFormat))) { // Work with the cropped image }
Image rotation in C#:
using (var rotatedImage = new Bitmap(originalImage)) { rotatedImage.RotateFlip(RotateFlipType.Rotate90FlipNone); // Work with the rotated image }
C# image compression:
EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, 50L); EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; originalImage.Save("compressed.jpg", GetEncoder(ImageFormat.Jpeg), encoderParams);
Transparent images in C#:
using (var transparentImage = new Bitmap(width, height, PixelFormat.Format32bppArgb)) { // Work with the transparent image }