I have a image with src = "data:image/png;base64...."
.
I want to convert this image into byte array byte[]
.
I have tried something like this:
string[] Base64 = ImageData.Split(new char[] { ',' });
byte[] imageBytes = System.Convert.FromBase64String(Base64[1].ToString());
What am I doing wrong here?
C# 8 version, without using Regex
or MemoryStream
:
var base64Image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAJFBMVEUAAACAgIAAAAD/AACAAAAAAP8AgAAA/wAAAICAgAD//wD///9wmW9uAAAAAXRSTlMAQObYZgAAAAFiS0dECx/XxMAAAAAHdElNRQfiBhoANycSsUctAAAA60lEQVQoz53Qv07DMBAG8DtH2X2JsscfaaFMIe4TFB4gRLLEzNAHYCA7ElLnbGVkw0+JnYSqDVu/LT9d7o+JrgovQf2rWJbUaiGalZx/J1QzJESfhuhaEGLmujKh/GEUyNwi4dzi0e6A+FdKJVvOK2t3e5ipRSm2qewW/XssaVPKSmlu7HY9geaUM+DJNhMoatlFqXDbv5mxRSsuwwHY969mvLVopbtzL8B6HMuKi2esXLc5TnsQgwt8uu7eD2baXZAF+Pjy3zNQPOQA74e/e0nC2I33OAFxoOOPOX+msNtwAVE0XcoSSOi6/ALgpCd992FfggAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxOC0wNi0yNlQwMDo1NTozOS0wNDowMAwZ2oMAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTgtMDYtMjZUMDA6NTU6MzktMDQ6MDB9RGI/AAAAAElFTkSuQmCC";
var offset = base64Image.IndexOf(',') + 1;
var imageInBytes = Convert.FromBase64String(base64Image[offset..^0]);
This was originally posted in the question itself by the OP. It was edited out of the question and into an answer.
Here is how I fixed it:
var base64Data = Regex.Match(ImageData.ImageURL, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
byte[] imageBytes = Convert.FromBase64String(base64Data);
I have no clue why you want to have the image as a byte-array, but think abour Memorystreams. This example is in vb.net:
Private Function GetImageByteArray(im As Image) As Byte()
Try
Using st As System.IO.MemoryStream = New System.IO.MemoryStream
im.Save(st, Imaging.ImageFormat.Raw)
Return st.ToArray
End Using
Finally
GC.Collect()
End Try
End Function
private byte[] GetImageByteArray(Image im)
{
try
{
using(MemoryStream st = new MemoryStream())
{
im.save(st, ImageFormat.Raw);
return st.toarray();
}
}
finally
{
GC.Collect();
}
}
But the described problem is more like converting data from a string into a byte-array.
image im;
using memorystream st = new memorystream(Convert.FromBase64String(data.substring(data.firstindexof(',')))
{im = image.fromstream(st);}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.