C # converts image data to byte array

I have an image with src = "data:image/png;base64...." .

I want to convert this image to byte[] array.

I tried something like this:

 string[] Base64 = ImageData.Split(new char[] { ',' }); byte[] imageBytes = System.Convert.FromBase64String(Base64[1].ToString()); 

But I think I'm doing something wrong.

Please, help.

UPDATE

Here is how I fixed it:

 var base64Data = Regex.Match(ImageData.ImageURL, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value; byte[] imageBytes = Convert.FromBase64String(base64Data); 
+6
source share
1 answer

I don't know why you want the image to be a byte array, but think about Memorystreams. This example is provided in the vb.net file:

 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 to a byte array.

 image im; using memorystream st = new memorystream(Convert.FromBase64String(data.substring(data.firstindexof(','))) {im = image.fromstream(st);} 
-1
source

Source: https://habr.com/ru/post/986151/


All Articles