How to convert Byte [] image to Base64string using JavaScript

I want to display an image from sql db on my web page, I got an image in the format {bytes [6317]} How to convert it to Base64string .

+5
source share
3 answers

Try this code,

byte[] imgBytes = (byte[])yourbytedata; string base64String = Convert.ToBase64String(imgBytes, 0, imgBytes.Length); string htmlstr = "data:image/png;base64," + base64String; 
+3
source

try it

 Byte[] bytes = File.ReadAllBytes("path"); String file = Convert.ToBase64String(bytes); And correspondingly, read back to file: Byte[] bytes = Convert.FromBase64String(b64Str); File.WriteAllBytes(path, bytes); 
+2
source

Javascript approach with Base64.js library

Since u indicated that u wants to convert it using JavaScript, you can do this using the Base64 JavaScript library. It has the following methods:

toByteArray - takes a base64 string and returns an array of bytes

and

fromByteArray - takes a byte array and returns a base64 string

Here is an example of how you could do this. First, back from ASP.NET MVC as the answer:

 return Json(new { Img = imageBytes }, JsonRequestBehavior.AllowGet); 

And then on the client, you can use the jQuery getJson () function to get the JSON response from MVC ImageController:

 $.getJSON("/Image",function(result){ $.each(result, function(i, field){ var byteArray = result.Img; var base64 = base64js.fromByteArray(byteArray); $("#mainimg").attr('src', 'data:image/jpeg;base64,' + base64); }); }); 

You can download the base64.js library from here:

https://github.com/beatgammit/base64-js

C # Conversion Approach

If you don't like the base64 javascript approach, you can convert the byte array on the server using C # using:

 String base64string = Convert.ToBase64String(imageBytes); return Json(new { Img = base64string }, JsonRequestBehavior.AllowGet); 

This will return a Base64 string as a result of the JSON Result. Then you can easily set the img source from jQuery, as shown in the Javascript Approach example.

0
source

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


All Articles