20 December, 2011
0 Comments
1 category
If you want to convert an Image to a byte array in C#, you can use the following extension method:
[TestMethod] public void Test() { Image image = null; // Supply your image here. byte[] bytes = image.ToBytes(); }
using System.Drawing; using System.Drawing.Imaging; using System.IO; namespace Services.Extensions { /// <summary> /// Extensions to the [System.Drawing.Image] class /// </summary> public static class ImageExtensions { /// <summary> /// Converts an image to an array of bytes. /// </summary> /// <param name="image">The image.</param> /// <returns></returns> public static byte[] ToBytes(this Image image) { byte[] result = null; using (var stream = new MemoryStream()) { image.Save(stream, image.RawFormat as ImageFormat); result = stream.ToArray(); } return result; } } }
Tags: C#
Category: Uncategorized