반응형

1. binary to image

convert binary source to image

<!--HTML Source-->
<img id="imgPreview" src="">
//javascript source
let binarySrc = 'AB4AA…6HNrfUH/cbXQYCRHJ/v8HL9i0B/qBtAMAAAAASUVORK5CYII';
document.getElementById("imgPreview").src = "data:image/png;base64," + binarySrc;

 

2. binary image to file 

convert image with binary source to file

<!--image html source -->
<img id="imgPreview" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB4AAAAQ3CAIAAACW5+TB">
imageToFile(document.getElementById("imgPreview").src);

function imageToFile(imgsrc){
//atob : base64로 인코딩된 src 디코딩
let bstr = atob(imgsrc.split(',')[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);

while(n--){
    u8arr[n] = bstr.charCodeAt(n);
}

let file = new File([u8arr],'imgFile.png',{type:'mime'});
console.log(file);
console.log(file.name);
//javascript 보안상 file을 input type file value에 할당할 수는 없음.
}

 

3. file to image (for previewing image )

convert file to image

shows the selected file as a preview

<!--HTML Source-->
<input type="file" id="file">
<img id="imgPreview" src="">
//파일 변경 시 미리보기 변경
$('#file').change(function(){
    readImage();
})


function readImage() {
    if(document.getElementById('file').files[0]){
        const reader = new FileReader();
        reader.onload = e => {
             const previewImage = document.getElementById('imgPreview')
             imgPreview.src = e.target.result
         }
        reader.readAsDataURL(document.getElementById('file').files[0])
}
반응형

+ Recent posts