K
K
KzLIFE2017-04-01 11:26:08
Character encoding
KzLIFE, 2017-04-01 11:26:08

How to correctly convert an image to Base64 for subsequent display in a browser?

Graphics graph = null;

var bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

graph = Graphics.FromImage(bmp);

graph.CopyFromScreen(0, 0, 0, 0, bmp.Size);

var ms = new MemoryStream();

bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

string convertedImg = Convert.ToBase64String(ms.ToArray(), Base64FormattingOptions.None);

At the output I get base64 when I insert it into the browser I get decay (
<img alt="" src="data:image/png;base64, CONVERTED_BASE64"/>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Tom Nolane, 2017-04-01
@tomnolane

here is my code:

Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

            Graphics graphics = Graphics.FromImage(printscreen as Image);

            graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);

            var ms = new MemoryStream();

            printscreen.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 

            string convertedImg = Convert.ToBase64String(ms.ToArray(), Base64FormattingOptions.None);

I get the output:
I insert it manually into the browser (ps without spaces , like you
<img alt="" src="data:image/png;base64,ТУТ_ПРОБЕЛА_У_ВАС CONVERTED_BASE64"/>
between base64 and CONVERTED_BASE64 )
I get:
but I get a screenshot from Visual Studio

S
svetlov97, 2017-05-28
@svetlov97

God, it's so hard. Just use FileReader.readAsDataURL()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question