简体   繁体   中英

I get an error “Parameter is not valid” when trying to convert byte to image

This is my code:

string photo = "somedata";
byte[] byt = System.Text.Encoding.UTF8.GetBytes(photo);

string strModified = Convert.ToBase64String(byt);
byte[] photoData = Convert.FromBase64String(strModified);
Image img = cnvrtToImg(photoData);

public Image cnvrtToImg(byte[] byteArrayIn)
{
     using (MemoryStream mStream = new MemoryStream(byteArrayIn))
     {
          return Image.FromStream(mStream);
     }
}

When the method cnvrtToImg is invoked, I get an error

Parameter is not valid

Please give me a solution

I think that System.Text.Encoding.UTF8 is not for image data, it is for text, not binary data. UTF8 just can't do some binary sequence. Base64 is the choice if you need convert binary to text. I test with this, and confirm the cnvrtToImg is correct:

class Program
{
    public static Image cnvrtToImg(byte[] byteArrayIn)
    {
        using (MemoryStream mStream = new MemoryStream(byteArrayIn))
        {
            return Image.FromStream(mStream);
        }
    }
    static void Main(string[] args)
    {
        using (var file = File.Open(@"D:\0.jpg", FileMode.Open))
        {
            var buffer = new byte[file.Length];
            file.Read(buffer, 0, (int) file.Length);
            cnvrtToImg(buffer);
        }
    }
}

//finish

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM