简体   繁体   English

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

[英]convert base64 to image in javascript/jquery

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.我正在搜索谷歌这么多网站,但它不起作用,并且该代码不适合我的要求。

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”,这里是内心和平的兼容性表

This is not exactly the OP's scenario but an answer to those of some of the commenters. 这不是OP的情况,而是对一些评论者的回答。 It is a solution based on Cordova and Angular 1, which should be adaptable to other frameworks like jQuery. 它是基于Cordova和Angular 1的解决方案,应该适用于其他框架,如jQuery。 It gives you a Blob from Base64 data which you can store somewhere and reference it from client side javascript / html. 它为您提供了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). 使用jpg和pdf文件(至少这是我测试的)。 Should work with other mimetypes/contenttypes too. 应该与其他mimetypes / contenttypes一起使用。 Check the browsers and their versions you aim for, they need to support Uint8Array, Blob and atob. 检查您的目标浏览器及其版本,他们需要支持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. 我希望这能使每个人都朝着正确的方向前进。

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

Html HTML

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

Js JS

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

Have to add this based on @Joseph's answer. 必须根据@Joseph的答案添加这个。 If someone want to create image object: 如果有人想要创建图像对象:

var image = new Image();
image.onload = function(){
   console.log(image.width); // image is loaded and we have image width 
}
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);

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);

}

Came to the following solution (please notice - I have not tested on across all browsers).来到以下解决方案(请注意 - 我尚未在所有浏览器上进行测试)。

    // first convert to blob
    const dataToBlob = async (imageData) => {
      return await (await fetch(imageData)).blob();
    };
    
    const blob = await dataToBlob(destination.value);
    
    // then create URL object
    const url = URL.createObjectURL(blob);

Hope it helps someone:)希望它可以帮助某人:)

Inspiration sources:灵感来源:

Creating a BLOB from a Base64 string in JavaScript 从 JavaScript 中的 Base64 字符串创建 BLOB

https://blog.logrocket.com/cropping-images-in-the-browser-with-vue-js/ https://blog.logrocket.com/cropping-images-in-the-browser-with-vue-js/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM