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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With