Вопрос

I am getting an exception when trying to convert a base64 string to a byte array. I am converting an Image to a byte array then to a base64 string, then encrypting it and storing it in a file. Then I am attempting to convert the base64 string back to a byte array in a MemoryStream, and recreating the image. I am getting a FormatException here:

byte[] imgBytes = Convert.FromBase64String(str);

Here is the full code for the two main functions:

public string ImageToString(Image img)
{
     using (MemoryStream ms = new MemoryStream())
     {
          img.Save(ms, ImageFormat.Jpeg);

          return Convert.ToBase64String(ms.ToArray());
     }
}

public Image StringToImage(String str)
{            
     int lent = str.Length;
     byte[] imgBytes = Convert.FromBase64String(str);
     MemoryStream ms = new MemoryStream(imgBytes, 0, imgBytes.Length);

     ms.Write(imgBytes, 0, imgBytes.Length);
     return Image.FromStream(ms, true);
}

Here is the beginning and end of the base64 string I am trying to convert.... G>/9j/4AAQSkZJRgABAQEAYABgAAD .... Uh+8fxpT/B9KAP/2Q==

Any ideas are greatly appreciated!

Это было полезно?

Решение

The problem is that your string got corrupted somewhere along the line. That's not a base64 string, as you can see by the second charcter >, which does not occur in a base64 string.


Side note: Your function creates a memory stream containing the data, then writes the data to the memory stream again. Then you try to read from the memory stream without resetting the position to the beginning of the stream.

Just create the memory stream and read from it:

public Image StringToImage(String str) {            
  byte[] imgBytes = Convert.FromBase64String(str);
  return Image.FromStream(new MemoryStream(imgBytes), true);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top