[c#] Fastest way to convert Image to Byte array

I am making Remote Desktop sharing application in which I capture an image of the Desktop and Compress it and Send it to the receiver. To compress the image I need to convert it to a byte[].

Currently I am using this:

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
    return  ms.ToArray();
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
     MemoryStream ms = new MemoryStream(byteArrayIn);
     Image returnImage = Image.FromStream(ms);
     return returnImage;
}

But I don't like it because I have to save it in a ImageFormat and that may also use up resources (Slow Down) as well as produce different compression results.I have read on using Marshal.Copy and memcpy but I am unable to understand them.

So is there any other method to achieve this goal?

This question is related to c# memory bitmap bytearray

The answer is


public static byte[] ReadImageFile(string imageLocation)
    {
        byte[] imageData = null;
        FileInfo fileInfo = new FileInfo(imageLocation);
        long imageFileLength = fileInfo.Length;
        FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        imageData = br.ReadBytes((int)imageFileLength);
        return imageData;
    }

public static class HelperExtensions
{
    //Convert Image to byte[] array:
    public static byte[] ToByteArray(this Image imageIn)
    {
        var ms = new MemoryStream();
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return ms.ToArray();
    }

    //Convert byte[] array to Image:
    public static Image ToImage(this byte[] byteArrayIn)
    {
        var ms = new MemoryStream(byteArrayIn);
        var returnImage = Image.FromStream(ms);
        return returnImage;
    }
}

There is a RawFormat property of Image parameter which returns the file format of the image. You might try the following:

// extension method
public static byte[] imageToByteArray(this System.Drawing.Image image)
{
    using(var ms = new MemoryStream())
    {
        image.Save(ms, image.RawFormat);
        return ms.ToArray();
    }
}

The fastest way i could find out is this :

var myArray = (byte[]) new ImageConverter().ConvertTo(InputImg, typeof(byte[]));

Hope to be useful


I'm not sure if you're going to get any huge gains for reasons Jon Skeet pointed out. However, you could try and benchmark the TypeConvert.ConvertTo method and see how it compares to using your current method.

ImageConverter converter = new ImageConverter();
byte[] imgArray = (byte[])converter.ConvertTo(imageIn, typeof(byte[]));

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to memory

How does the "view" method work in PyTorch? How do I release memory used by a pandas dataframe? How to solve the memory error in Python Docker error : no space left on device Default Xmxsize in Java 8 (max heap size) How to set Apache Spark Executor memory What is the best way to add a value to an array in state How do I read a large csv file with pandas? How to clear variables in ipython? Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

Examples related to bitmap

How to solve java.lang.OutOfMemoryError trouble in Android Save and retrieve image (binary) from SQL Server using Entity Framework 6 How to create bitmap from byte array? Fastest way to convert Image to Byte array How to save a bitmap on internal storage Android set bitmap to Imageview Save bitmap to file function How to resize Image in Android? Android Bitmap to Base64 String Android load from URL to Bitmap

Examples related to bytearray

How to create bitmap from byte array? Put byte array to JSON and vice versa Byte Array to Hex String Java ByteBuffer to String Fastest way to convert Image to Byte array How to store a byte array in Javascript Conversion from byte array to base64 and back How do I print bytes as hexadecimal? How to convert image into byte array and byte array to base64 String in android? How to convert a byte array to a hex string in Java?