Convert an array of bytes into an image with JavaScript

0

I have the following situation. I am using a Google API to generate dynamic charts (Google Org Chart), my project is made in asp.net mvc, but this time I only use JS.

The problem that arises is that I need to show an image that I have hosted in my database with the SQL Server manager, the data type is varbinary ...

When I try to show it at the moment I can only show the byte array but I would like to know if someone could support me to make that conversion.

The problem is specifically in the part of var Image.

<!-- Scripts JS -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>

<script type="text/javascript">
    google.load("visualization", "1", { packages: ["orgchart"] });
    google.setOnLoadCallback(drawChart);

    function drawChart() {
        $.ajax({

            type: "POST",
            url: "/Conocenos/Organigrama_Json",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (dt) {

                var dataArray = [];

                $.each(dt, function (i, item) {
                    dataArray.push([item.IDSERVPUB, item.NOMBREPERSONAL, item.NOMBRAMIENTO, item.NIVEL, item.FOTOPERSONAL]);
                });

                var data = new google.visualization.DataTable();

                data.addColumn('string', 'Entity');
                data.addColumn('string', 'ReportEntity');
                data.addColumn('string', 'ToolTip');


                for (var i = 0; i < dataArray.length; i++) {
                    //no cambiar nombre de variables
                    var Employee_ID = dataArray[i][0].toString();
                    var Employee_Name = dataArray[i][1];
                    var Title = dataArray[i][2];
                    var ReportTo = dataArray[i][3] != null ? dataArray[i][3].toString() : '';
                    //necesito convertir este arreglo de bytes en una imagen
                    var Image = dataArray[i][4]; // solo muestro el arreglo 


                    //si el valor el null que no lo muestre en el diagrama
                    if (Employee_Name == null) {
                        Employee_Name = "";
                    }
                    data.addRows([[{
                        v: Employee_ID,
                        f: Employee_Name + '<br/><b>' + Title + '</b>' + '<br/><b>' + Image
                                           
                    }, ReportTo, Title]]);
                }


                var chart = new google.visualization.OrgChart($("#chartOrg")[0]);
                chart.draw(data, { allowHtml: true });

            },
            failure: function (dt) {
                alert(dt);
            },
            error: function (dt) {
                alert(dt);
            }
        });
    }
</script>

    
asked by Galaviz Arroyo 22.11.2018 в 17:49
source

1 answer

3

First you have to know what kind of image it is ( jpeg , gif or png ), then you have to code the bytes in Base64 and finally you have to put it in the attribute src of a <img> as follows:

<img src="data:image/__FORMATO__;base64,__BYTES_EN_BASE64__">

In your code you have the image, in var Image = dataArray[i][4]; . You would have to code it in Base64 with var Image_Base64 = btoa(Image) , but it is not compatible with all browsers, so I recommend saving the images already encoded in the database.

But ... you lack the type of image. You can save it in the database or convert all the images to the format you prefer before saving them in the database.

Because of your code, it seems like Imagen is not a binary string, but an array of bytes. If so, you would need to convert it first, if you decide to use javascript and btoa() :

function bin2string(array){
    var result = "";
    for(var i = 0; i < array.length; ++i){
        result+= (String.fromCharCode(array[i]));
    }
    return result;
}
var Imagen_Bin_String = bin2string(Imagen);
var Imagen_Base64 = btoa(Imagen_Bin_String);

Note: the bin2string() function was taken from link .

data.addRows( [ [
    {
        v: Employee_ID,
        f: Employee_Name +
           '<br/><b>' +
           Title + '</b>' +
           '<br/><b>' +
           '<img src="data:image/jpg;base64,' + Imagen_Base64 + '">'
    },
    ReportTo,
    Title
] ] );
    
answered by 22.11.2018 / 18:00
source