본문 바로가기

javascript

자바스크립트 Base64로 이미지 파일 바이트로 바꾸기

728x90

==========

이미지 미리보기

 

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>이미지와 Base64 문자열 표시</title>
  <style>
    .img_xw0h3bpjh89ned51cv {
      max-width: 300px;
      display: block;
      margin: 10px 0;
    }
    .textarea_xw0h3bpjh89ned51cv {
      width: 100%;
      height: 150px;
    }
  </style>
</head>
<body>
  <input type="file" id="fileInput" accept="image/*">
  <img id="preview" src="" class="img_xw0h3bpjh89ned51cv" alt="이미지 미리보기">
  <textarea class="textarea_xw0h3bpjh89ned51cv" id="base64Text" placeholder="Base64 문자열이 여기에 표시됩니다."></textarea>

  <script>
    const fileInput = document.getElementById('fileInput');
    const preview = document.getElementById('preview');
    const base64Text = document.getElementById('base64Text');

    fileInput.addEventListener('change', function(event) {
      const file = event.target.files[0];
      if (!file) return;

      const reader = new FileReader();
      reader.onload = function(e) {
        const base64String = e.target.result;
        preview.src = base64String;
        base64Text.value = base64String;
      };

      reader.readAsDataURL(file);
    });
  </script>
</body>
</html>

 

 

 

 


다운로드
이미지 미리보기

 

 

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Base64 이미지 표시 및 다운로드</title>
</head>
<body>
  <textarea id="base64Text" placeholder="Base64 문자열을 입력하세요." style="width:100%; height:150px;"></textarea>
  <br>
  <button id="showBtn">이미지 표시</button>
  <a id="downloadLink" download="image.png" style="margin-left:10px; display:inline-block;">다운로드</a>
  <br>
  <img id="preview" alt="이미지 미리보기" style="max-width:100%; margin-top:10px;">
  
  <script>
    const base64Text = document.getElementById('base64Text');
    const showBtn = document.getElementById('showBtn');
    const downloadLink = document.getElementById('downloadLink');
    const preview = document.getElementById('preview');

    showBtn.addEventListener('click', () => {
      const dataUrl = base64Text.value.trim();
      if(dataUrl) {
        preview.src = dataUrl;
        downloadLink.href = dataUrl;
      }
    });
  </script>
</body>
</html>

 

==========

728x90