Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip out header from base 64 image in C#?

Tags:

c#

base64

I have following base 64 image:

var image='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA0gA...';

I am using Convert.FromBase64String()to convert this to bytes:

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

But before this, I need to strip out the header of Base 64 string (i.e data:image/png;base64). I am doing this using:

string convert = image.Replace("data:image/png;base64,", string.Empty);

I can write the same statement for all image extensions separately, but these images are very large and scanning through each one seems inefficient.

I searched this solution which uses regular expression in PHP to cut off the header part, while other answer in PHP uses an inbuilt method get_contents.

My Question is: Is there any inbuilt method to get only contents of base 64 url in C#? If not, then is there any generalized way to strip out header for all extensions?

like image 893
Karan Desai Avatar asked Sep 01 '16 09:09

Karan Desai


2 Answers

You could try something like this:

string result = Regex.Replace(image, @"^data:image\/[a-zA-Z]+;base64,", string.Empty);

this should catch the different extensions. I haven't tested this though so it might need some fiddling with.

like image 153
Ronan Avatar answered Sep 21 '22 09:09

Ronan


Since you know the only instance of , in the string will be the separator between the preamble and the data, you could do it without regex like this:

string convert = image.Substring(image.IndexOf(",") + 1);
like image 37
Blorgbeard Avatar answered Sep 19 '22 09:09

Blorgbeard