如何在javascript中将字节数组转换为图像 [英] How do i convert byte array to image in javascript

查看:180
本文介绍了如何在javascript中将字节数组转换为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Java脚本将字节数组转换为图像,以便在前端显示它.我正在使用blob将图像插入mysql数据库.在保存之前,图像已被转换为字节数组.

I want to convert byte array to image using Javascript for displaying it in frontend. I am inserting an image into mysql database using blob. The image has been converted to byte array before saving.

我正在使用json数组检索所有表值,并使用javascript显示.在json数组中,我还将此图像也添加为bytearray.

And I'm retrieving all the table values using json array and displaying using javascript. In the json array i'am adding this image as bytearray also.

我能够检索其他值,但是不能将此字节数组显示为图像.

I am able to retrieve the other values, but not able to display this byte array as image.

如何将此字节数组转换为javascript中的图像,以便可以使用html显示它?

How do i convert this byte array to an image in javascript so that i can display it using html?

以上代码:

$scope.uploadFile = function (input) {

        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {

                //Sets the Old Image to new New Image
                $('#itemImage').attr('src', e.target.result);

                //Create a canvas and draw image on Client Side to get the byte[] equivalent
                var canvas = document.createElement("canvas");
                var imageElement = document.createElement("img");

                imageElement.setAttribute('src', e.target.result);
                canvas.width = imageElement.width;
                canvas.height = imageElement.height;
                var context = canvas.getContext("2d");
                context.drawImage(imageElement, 0, 0);
                var base64Image = canvas.toDataURL("image/jpeg");

                //Removes the Data Type Prefix 
                //And set the view model to the new value
                $scope.itemImage = base64Image.replace(/data:image\/jpeg;base64,/g, '');
            }

            //Renders Image on Page
            reader.readAsDataURL(input.files[0]);
        }
    };

推荐答案

如果图像很小,则可以在base 64中对其进行编码,并将其作为img标签的src.

If the image is small you can encode it in base 64 and put that as the src of an img tag.

这篇关于如何在javascript中将字节数组转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆