将base64转换为javascript / jquery中的图像

时间:2022-12-02 21:29:24

I have written some code for image capturing using javascript/jquery Below is the code:

我用javascript / jquery编写了一些图像捕获代码。下面是代码:

function capture_image(){ 
    alert("capture_image");
    var p = webcam.capture();
    webcam.save();           
    alert("capture complete "+p); //getting true here


     var img = canvas.toDataURL("image");
    var item_image = img.replace(/^data:image\/(png|jpg);base64,/, "") ; 
    alert("item_image"+item_image);
}

The item_image print the base64 format, How to convert that base64 to image and how to use that path in javascript clientside.

item_image打印base64格式,如何将base64转换为图像以及如何在javascript客户端中使用该路径。

Am searching google so many websites but its not working and that code is not suitable for my requirement.

我搜索谷歌这么多的网站,但它不工作,该代码不适合我的要求。

5 个解决方案

#1


73  

You can just create an Image object and put the base64 as its src, including the data:image... part like this:

您可以创建一个Image对象并将base64作为其src,包括data:image ...如下所示:

var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);

It's what they call "Data URIs" and here's the compatibility table for inner peace.

这就是他们所谓的“数据URI”,这里是内心和平的兼容性表。

#2


9  

This is not exactly the OP's scenario but an answer to those of some of the commenters. It is a solution based on Cordova and Angular 1, which should be adaptable to other frameworks like jQuery. It gives you a Blob from Base64 data which you can store somewhere and reference it from client side javascript / html.

这不是OP的情况,而是对一些评论者的回答。它是基于Cordova和Angular 1的解决方案,它应该适用于其他框架,如jQuery。它为您提供了Base64数据的Blob,您可以将其存储在某处并从客户端javascript / html引用它。

It also answers the original question on how to get an image (file) from the Base 64 data:

它还回答了关于如何从Base 64数据中获取图像(文件)的原始问题:

The important part is the Base 64 - Binary conversion:

重要的部分是Base 64 - 二进制转换:

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

Slicing is required to avoid out of memory errors.

需要切片以避免内存不足错误。

Works with jpg and pdf files (at least that's what I tested). Should work with other mimetypes/contenttypes too. Check the browsers and their versions you aim for, they need to support Uint8Array, Blob and atob.

使用jpg和pdf文件(至少这是我测试的)。应该与其他mimetypes / contenttypes一起使用。检查您的目标浏览器及其版本,他们需要支持Uint8Array,Blob和atob。

Here's the code to write the file to the device's local storage with Cordova / Android:

以下是使用Cordova / Android将文件写入设备本地存储的代码:

...
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {

                    // Setup filename and assume a jpg file
                    var filename = attachment.id + "-" + (attachment.fileName ? attachment.fileName : 'image') + "." + (attachment.fileType ? attachment.fileType : "jpg");
                    dirEntry.getFile(filename, { create: true, exclusive: false }, function(fileEntry) {
                        // attachment.document holds the base 64 data at this moment
                        var binary = base64toBlob(attachment.document, attachment.mimetype);
                        writeFile(fileEntry, binary).then(function() {
                            // Store file url for later reference, base 64 data is no longer required
                            attachment.document = fileEntry.nativeURL;

                        }, function(error) {
                            WL.Logger.error("Error writing local file: " + error);
                            reject(error.code);
                        });

                    }, function(errorCreateFile) {
                        WL.Logger.error("Error creating local file: " + JSON.stringify(errorCreateFile));
                        reject(errorCreateFile.code);
                    });

                }, function(errorCreateFS) {
                    WL.Logger.error("Error getting filesystem: " + errorCreateFS);
                    reject(errorCreateFS.code);
                });
...

Writing the file itself:

编写文件本身:

function writeFile(fileEntry, dataObj) {
    return $q(function(resolve, reject) {
        // Create a FileWriter object for our FileEntry (log.txt).
        fileEntry.createWriter(function(fileWriter) {

            fileWriter.onwriteend = function() {
                WL.Logger.debug(LOG_PREFIX + "Successful file write...");
                resolve();
            };

            fileWriter.onerror = function(e) {
                WL.Logger.error(LOG_PREFIX + "Failed file write: " + e.toString());
                reject(e);
            };

            // If data object is not passed in,
            // create a new Blob instead.
            if (!dataObj) {
                dataObj = new Blob(['missing data'], { type: 'text/plain' });
            }

            fileWriter.write(dataObj);
        });
    })
}

I am using the latest Cordova (6.5.0) and Plugins versions:

我使用的是最新的Cordova(6.5.0)和插件版本:

I hope this sets everyone here in the right direction.

我希望这能让每个人都朝着正确的方向前进。

#3


6  

var src = "data:image/jpeg;base64,";
src += item_image;
var newImage = document.createElement('img');
newImage.src = src;
newImage.width = newImage.height = "80";
document.querySelector('#imageContainer').innerHTML = newImage.outerHTML;//where to insert your image

#4


5  

Html

HTML

<img id="imgElem"></img>

Js

JS

string baseStr64="/9j/4AAQSkZJRgABAQE...";
imgElem.setAttribute('src', "data:image/jpg;base64," + baseStr64);

#5


1  

One quick and easy way:

一种快捷简便的方法:

function paintSvgToCanvas(uSvg, uCanvas) {

    var pbx = document.createElement('img');

    pbx.style.width  = uSvg.style.width;
    pbx.style.height = uSvg.style.height;

    pbx.src = 'data:image/svg+xml;base64,' + window.btoa(uSvg.outerHTML);
    uCanvas.getContext('2d').drawImage(pbx, 0, 0);

}

#1


73  

You can just create an Image object and put the base64 as its src, including the data:image... part like this:

您可以创建一个Image对象并将base64作为其src,包括data:image ...如下所示:

var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);

It's what they call "Data URIs" and here's the compatibility table for inner peace.

这就是他们所谓的“数据URI”,这里是内心和平的兼容性表。

#2


9  

This is not exactly the OP's scenario but an answer to those of some of the commenters. It is a solution based on Cordova and Angular 1, which should be adaptable to other frameworks like jQuery. It gives you a Blob from Base64 data which you can store somewhere and reference it from client side javascript / html.

这不是OP的情况,而是对一些评论者的回答。它是基于Cordova和Angular 1的解决方案,它应该适用于其他框架,如jQuery。它为您提供了Base64数据的Blob,您可以将其存储在某处并从客户端javascript / html引用它。

It also answers the original question on how to get an image (file) from the Base 64 data:

它还回答了关于如何从Base 64数据中获取图像(文件)的原始问题:

The important part is the Base 64 - Binary conversion:

重要的部分是Base 64 - 二进制转换:

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

Slicing is required to avoid out of memory errors.

需要切片以避免内存不足错误。

Works with jpg and pdf files (at least that's what I tested). Should work with other mimetypes/contenttypes too. Check the browsers and their versions you aim for, they need to support Uint8Array, Blob and atob.

使用jpg和pdf文件(至少这是我测试的)。应该与其他mimetypes / contenttypes一起使用。检查您的目标浏览器及其版本,他们需要支持Uint8Array,Blob和atob。

Here's the code to write the file to the device's local storage with Cordova / Android:

以下是使用Cordova / Android将文件写入设备本地存储的代码:

...
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {

                    // Setup filename and assume a jpg file
                    var filename = attachment.id + "-" + (attachment.fileName ? attachment.fileName : 'image') + "." + (attachment.fileType ? attachment.fileType : "jpg");
                    dirEntry.getFile(filename, { create: true, exclusive: false }, function(fileEntry) {
                        // attachment.document holds the base 64 data at this moment
                        var binary = base64toBlob(attachment.document, attachment.mimetype);
                        writeFile(fileEntry, binary).then(function() {
                            // Store file url for later reference, base 64 data is no longer required
                            attachment.document = fileEntry.nativeURL;

                        }, function(error) {
                            WL.Logger.error("Error writing local file: " + error);
                            reject(error.code);
                        });

                    }, function(errorCreateFile) {
                        WL.Logger.error("Error creating local file: " + JSON.stringify(errorCreateFile));
                        reject(errorCreateFile.code);
                    });

                }, function(errorCreateFS) {
                    WL.Logger.error("Error getting filesystem: " + errorCreateFS);
                    reject(errorCreateFS.code);
                });
...

Writing the file itself:

编写文件本身:

function writeFile(fileEntry, dataObj) {
    return $q(function(resolve, reject) {
        // Create a FileWriter object for our FileEntry (log.txt).
        fileEntry.createWriter(function(fileWriter) {

            fileWriter.onwriteend = function() {
                WL.Logger.debug(LOG_PREFIX + "Successful file write...");
                resolve();
            };

            fileWriter.onerror = function(e) {
                WL.Logger.error(LOG_PREFIX + "Failed file write: " + e.toString());
                reject(e);
            };

            // If data object is not passed in,
            // create a new Blob instead.
            if (!dataObj) {
                dataObj = new Blob(['missing data'], { type: 'text/plain' });
            }

            fileWriter.write(dataObj);
        });
    })
}

I am using the latest Cordova (6.5.0) and Plugins versions:

我使用的是最新的Cordova(6.5.0)和插件版本:

I hope this sets everyone here in the right direction.

我希望这能让每个人都朝着正确的方向前进。

#3


6  

var src = "data:image/jpeg;base64,";
src += item_image;
var newImage = document.createElement('img');
newImage.src = src;
newImage.width = newImage.height = "80";
document.querySelector('#imageContainer').innerHTML = newImage.outerHTML;//where to insert your image

#4


5  

Html

HTML

<img id="imgElem"></img>

Js

JS

string baseStr64="/9j/4AAQSkZJRgABAQE...";
imgElem.setAttribute('src', "data:image/jpg;base64," + baseStr64);

#5


1  

One quick and easy way:

一种快捷简便的方法:

function paintSvgToCanvas(uSvg, uCanvas) {

    var pbx = document.createElement('img');

    pbx.style.width  = uSvg.style.width;
    pbx.style.height = uSvg.style.height;

    pbx.src = 'data:image/svg+xml;base64,' + window.btoa(uSvg.outerHTML);
    uCanvas.getContext('2d').drawImage(pbx, 0, 0);

}