반응형
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])
}
반응형
'코딩 관련 > Javascript와 jQuery, JSON' 카테고리의 다른 글
[Javascript] 비동기를 동기처리하기 / javascript 동기 처리 (0) | 2022.04.18 |
---|---|
jQuery Alias / jquery $ 변경 (0) | 2022.04.05 |
[JavaScript][Spring] form data 전송하기 / file 전송하기 / <form> 전송 (1) | 2021.11.09 |
[Javascript] javascript resources load / springboot resource / thymeleaf javascript path (0) | 2021.10.28 |
[Javacript] url 가져오기, url 파라미터 가져오기, url 쿼리스트링 가져오기 (0) | 2021.10.21 |