ProgramingTip

javascript / jquery에서 base64를 이미지로 변환

bestdevel 2020. 11. 4. 08:09
반응형

javascript / jquery에서 base64를 이미지로 변환


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

item_image는 base64 형식, base64를 이미지로 변환하는 방법 및 자바 펼쳐 클라이언트 측에서 해당 경로를 사용하는 방법을 인쇄합니다.

Google에서 너무 많은 웹 사이트를 검색하고 요구하지 않을 코드가 내 요구 사항에 적합하지 않습니다.


다음 과 같은 부분을 ​​포함 하여 Image객체를 만들고 base64를 .srcdata:image...

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

이것이 "데이터 URI"라고 부르는 것이 아니라 여기 에 내적 평화를위한 가 있습니다.


이 OP의 시나리오가 아니라 일부 댓글 작성자의 답변입니다. Cordova 및 Angular 1을 기반으로하는 솔루션으로 jQuery와 같은 다른 프레임 워크에 적용 할 수 있어야합니다. 어딘가에 저장하고 클라이언트 측 javascript / html에서 참조 할 수있는 Base64 데이터의 Blob을 제공합니다.

또한 Base 64 데이터에서 이미지 (파일)를 가져 오는 방법에 대한 원래 질문에 대답합니다.

중요한 부분은 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 });
}

메모리 부족 오류를 방지하기 위해 슬라이싱이 필요합니다.

jpg 및 pdf 파일로 작동합니다 (적어도 내가 테스트 한 것입니다). 다른 mimetypes / contenttypes 작동해야합니다. 목표로하는 브라우저와 버전을 확인하세요. Uint8Array, Blob 및 atob을 지원해야합니다.

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

파일 자체 작성 :

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

최신 Cordova (6.5.0) 및 플러그인 버전을 사용하고 있습니다.

여기에있는 모든 사람들이 올바른 방향으로 나아가기를 바랍니다.


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

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

Js

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

@Joseph의 답변에 따라 이것을 추가해야합니다. 누군가 이미지 개체를 만들고 싶다면 :

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

빠르고 쉬운 방법 :

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

}

참고 URL : https://stackoverflow.com/questions/21227078/convert-base64-to-image-in-javascript-jquery

반응형