SoFunction
Updated on 2025-03-01

Methods of converting C# byte array and Image


// Convert Image to Byte[]
        private byte[] ImageToByte(Image image)
        {
            ImageFormat format = ;
            using (MemoryStream ms = new MemoryStream())
            {
                if (())
                {
                    (ms, );
                }
                else if (())
                {
                    (ms, );
                }
                else if (())
                {
                    (ms, );
                }
                else if (())
                {
                    (ms, );
                }
                else if (())
                {
                    (ms, );
                }
                byte[] buffer = new byte[];
//() will change the Position of MemoryStream and need to re-seek to Begin
                (0, );
                (buffer, 0, );
                return buffer;
            }
        }

        // Convert Byte[] to Image
        private Image ByteToImage(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer);
            Image image = (ms);
            return image;
        }

        // Convert Byte[] to a picture
        private string CreateImageFromByte(string fileName, byte[] buffer)
        {
string file = fileName; //File name (excluding extension)
            Image image = ByteToImage(buffer);
            ImageFormat format = ;
            if (())
            {
                file += ".jpeg";
            }
            else if (())
            {
                file += ".png";
            }
            else if (())
            {
                file += ".bmp";
            }
            else if (())
            {
                file += ".gif";
            }
            else if (())
            {
                file += ".icon";
            }
//The file path directory must exist, otherwise you will create the directory first using Directory
            (file, buffer);
            return file;
        }