Convert Base64 string to jpeg image in C#

Asked

Viewed 1,076 times

1

How to convert a Base64 string to a jpeg image?

I saw some places talking to use one with namespace System.Drawing.Image.

But in my Visual Studio project you don’t see this class.

I have tested in several versions of . NET and nothing.

1 answer

5

Use the method FromBase64String class Convert to generate a array of bytes from the string in Base64.

With this byte array, create a new stream in memory of the class MemoryStream.

Having a stream you can use the method FromStream class Image.

To save the image to disk, it is possible to use some of the methods Save.


Note which class Image is in the namespace System.Drawing and is defined in Assemblies System.Drawing.dll.

So in addition to adding the using in the code, it is necessary to make sure that the DLL is referenced in the project.

using System.Drawing;
using System.Drawing.Imaging; // ImageFormat

...

var strBase64 = "stringbase64";
var imagem = Image.FromStream(new MemoryStream(Convert.FromBase64String(strBase64)));

// Um exemplo de como salvar, existem diversas formas
imagem.Save("C:\\temp\\imagem.jpg", ImageFormat.Jpeg);
  • System.Drawing.Common.dll is not required. This DLL is built-in for Mac kernel use System.Drawing made by .NET. The user will not be able to reference it...

  • 1

    @Cypherpotato I was thinking that it was one for . NET F and one for Core. Then I left the two, because before I left it _(ツ)_/ Btw, thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.