Conversion between image and byte array
Question: How to convert an image to a byte array, and how to convert a byte array back to an image?
Answer:
To convert an image to a byte array, you can use the following sample code:
<code class="language-csharp">public byte[] ImageToByteArray(System.Drawing.Image imageIn) { using (var ms = new MemoryStream()) { imageIn.Save(ms, imageIn.RawFormat); return ms.ToArray(); } }</code>
This code uses MemoryStream
to store the image and then converts it to a byte array.
To convert the byte array back to an image, you can also use a class like this:
<code class="language-csharp">public class ImageConverter { public ImageConverter() { } public Image ByteToImage(byte[] byteArrayIn) { using (var ms = new MemoryStream(byteArrayIn)) { Image returnImage = Image.FromStream(ms); return returnImage; } } public byte[] ImageToByte(Image imageIn) { using (var ms = new MemoryStream()) { imageIn.Save(ms, ImageFormat.Png); // 指定保存格式为PNG return ms.ToArray(); } } }</code>
This code provides a more structured way to perform conversion between images and byte arrays, and explicitly specifies the format in which the image is saved as PNG. You can modify ImageFormat
to choose a different format, such as JPEG or GIF, if needed.
The above is the detailed content of How to Convert Images to Byte Arrays and Back?. For more information, please follow other related articles on the PHP Chinese website!