Error: the magic number in the GZip header is incorrect

I have two methods, one of which I use to convert the image to a Base64 string so that I can store it in an XML tag, and the other to convert the Base64 string back to the image. I can convert the image to a string and save it in XML, but when I try to convert the string back to an image, I get the following error: "The magic number in the GZip header is incorrect. Make sure you go through the GZip stream."

Any thoughts on how to resolve this?

public static string ConvertToBase64String(Image Image, ImageFormat Format)
{
    MemoryStream stream = new MemoryStream();
    Image.Save(stream, Format);

    byte[] imageBytes = stream.ToArray();

    MemoryStream memStream = new MemoryStream();
    GZipStream zipStream = new GZipStream(memStream, CompressionMode.Compress);
    zipStream.Write(imageBytes, 0, imageBytes.Length);

    string imageString = Convert.ToBase64String(imageBytes);

    stream.Close();
    memStream.Close();

    return imageString;
}

public static Image Base64StringToImage(string ImageArray)
{
    byte[] base64String = Convert.FromBase64String(ImageArray);

    MemoryStream memStream = new MemoryStream(base64String);
    GZipStream zipStream = new GZipStream(memStream, CompressionMode.Decompress);
    zipStream.Read(base64String, 0, base64String.Length);

    ImageConverter ic = new ImageConverter();
    Image image = (Image)ic.ConvertFrom(base64String);

    memStream.Close();

    return image;
}
+3
source share
1 answer

I see some errors in the code.

, , , , 64-, (memStream.ToArray()), , zip- (imageBytes). , , .

, zip-, , zip-.

, Read. , , , . Read , , . Read , .

, , , . , , , , , . , , .

+6

Source: https://habr.com/ru/post/1740354/


All Articles