0

I am Trying to Convert a Base64 encoded string to A Png Image, But the Code Shows Exception of Parameter is Not Valid on Image.FromStream(). After Debugging i cam up with this error on MemoryStream Object "ReadTimeout = 'ms.ReadTimeout' threw an exception of type 'System.InvalidOperationException'" . I am stuck, Is there any Solution or Alternative to Convert String to Png in C#?

Here is My code

string code = "string";
var databytes = Encoding.Unicode.GetBytes(code);
var base64 = Convert.ToBase64String(databytes);
Byte[] Bytes = Convert.FromBase64String(base64);
//Stream bytes
MemoryStream ms = new MemoryStream(Bytes, 0, Bytes.Length);
//convert image

Image newImage = Image.FromStream(ms);
newImage.Save("~/Content/");    

2 Answers 2

1

Try this:

byte[] bytes = Convert.FromBase64String(base64);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
    image = Image.FromStream(ms);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can convert Base64 string into png in this way:

    byte[] bytes = Convert.FromBase64String(base64);

    Image image;
    using (MemoryStream ms = new MemoryStream(bytes))
    {
        image = Image.FromStream(ms);
        image.Save("~/Content/", System.Drawing.Imaging.ImageFormat.Png);
    }

6 Comments

I tried That , But As i mentioned Its is showing exception at Image.FromStream(ms) the Exception is ReadTimeout = 'ms.ReadTimeout' threw an exception of type 'System.InvalidOperationException'
I moved the image.Save part inside the using block and updated the answer. It can be fix your error.
I tried, But same Error {{"Parameter is not valid."} occurs at Image.FromStream(ms) line
Actually I am Converting a Partial View to String, And then i wan to Generate Png from That String
Did you tried to encode your string with UTF8? var databytes = Encoding.UTF8.GetBytes(code);
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.