Kay
Kay

Reputation: 3

Image cannot be converter from byte array

I have block code:

        Image x = Image.FromFile(@"C:\Users\Tung\Pictures\Untitled.png");
        ImageConverter _imageConverter = new ImageConverter();
        byte[] xByte = (byte[])_imageConverter.ConvertTo(x, typeof(byte[]));

        StreamWriter sw = new StreamWriter("textfile.txt");
        string base64String =  System.Convert.ToBase64String(xByte,0,xByte.Length);
        sw.WriteLine(base64String);
        sw.Close();

        StreamReader sr = new StreamReader("textfile.txt");
        string line = sr.ReadToEnd();

        byte[] byteArray = Encoding.UTF8.GetBytes(line);
        MemoryStream stream = new MemoryStream(byteArray);
        sr.Close();

        File.WriteAllBytes("F:\\YourFile1.png", byteArray);
        File.WriteAllBytes("F:\\YourFile2.png", xByte);

after run, YourFile1.png can not display and YourFile2.png display ok. I do not understand. Can you help me?

Upvotes: 0

Views: 109

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415600

This line is wrong:

byte[] byteArray = Encoding.UTF8.GetBytes(line);

The line variable here is a base64 encoded string, where each character represents 3/4 of a byte (6 bits to encode 64 possible values). But Encoding.UTF8.GetBytes() looks at each character in your string and produces a full byte for each character (more for non-ascii characters, but you won't have those here). It's not decoding the base64 data at all. You need to do this:

byte[] byteArray = Convert.FromBase64String(line);

Upvotes: 1

Related Questions