// ----------------------------------------------------------------------- // // Copyright (c) James South. // Licensed under the Apache License, Version 2.0. // // ----------------------------------------------------------------------- namespace ImageProcessor.Helpers.Extensions { #region Using using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; #endregion /// /// Extensions to the class /// public static class ImageExtensions { /// /// Converts an image to an array of bytes. /// /// The instance that this method extends. /// The to export the image with. /// A byte array representing the current image. public static byte[] ToBytes(this Image image, ImageFormat imageFormat) { BitmapData data = ((Bitmap)image).LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); int length = image.Width * image.Height * 4; byte[] byteArray = new byte[length]; if (data.Stride == image.Width * 4) { Marshal.Copy(data.Scan0, byteArray, 0, length); } else { for (int i = 0, l = image.Height; i < l; i++) { IntPtr p = new IntPtr(data.Scan0.ToInt32() + data.Stride * i); Marshal.Copy(p, byteArray, i * image.Width * 4, image.Width * 4); } } ((Bitmap)image).UnlockBits(data); return byteArray; } public static Image FromBytes(this Image image, byte[] bytes) { BitmapData data = ((Bitmap)image).LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); if (data.Stride == image.Width * 4) { Marshal.Copy(bytes, 0, data.Scan0, bytes.Length); } else { for (int i = 0, l = image.Height; i < l; i++) { IntPtr p = new IntPtr(data.Scan0.ToInt32() + data.Stride * i); Marshal.Copy(bytes, i * image.Width * 4, p, image.Width * 4); } } ((Bitmap)image).UnlockBits(data); return image; } } }