Clipboard add Image

by Sebastian Kay

HTML

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<div class="container mt-5">
  <div class="image-preview" id="imagePreview" style="display: none">
    <img id="previewImage" src="" alt="Image Preview" />
    <span class="close" id="removeImage">&times;</span>
    <div class="image-info" id="imageInfo"></div>
  </div>
  <form id="imageForm">
    <div class="form-group">
      <label for="textInput">Paste an image here:</label>
      <input
        type="text"
        class="form-control"
        id="textInput"
        placeholder="Paste image here..."
      />
    </div>
  </form>
</div>

CSS

.image-preview {
            position: relative;
            flex-direction: column;
            margin-bottom: 20px;
        }
        .image-preview img {
            max-width: 100px;
            height: auto;
        }
        .image-preview .close {
          position: absolute;
          top: -10px;
          left: 90px;
          background-color: #ab2020;
          border-radius: 50%;
          width: 20px;
          height: 20px;
          line-height: 1;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .image-info {
            margin-top: 10px;
            font-size: 14px;
            color: #6c757d;
        }

JavaScript

document.body.dataset.bsTheme = "dark";

document.addEventListener("DOMContentLoaded", function () {
  const textInput = document.getElementById("textInput")
  const imagePreview = document.getElementById("imagePreview")
  const previewImage = document.getElementById("previewImage")
  const removeImage = document.getElementById("removeImage")
  const imageInfo = document.getElementById("imageInfo")

  textInput.addEventListener("paste", function (event) {
    const items = (event.clipboardData || window.clipboardData).items
    for (let i = 0; i < items.length; i++) {
      if (items[i].kind === "file" && items[i].type.startsWith("image/")) {
        const file = items[i].getAsFile()
        const reader = new FileReader()

        reader.onload = function (e) {
          const base64Image = e.target.result
          previewImage.src = base64Image
          imagePreview.style.display = "flex"
          imageInfo.textContent = `File size: ${readableBytes(file.size)}`
        }

        reader.readAsDataURL(file)
      }
    }
  })

  removeImage.addEventListener("click", function () {
    previewImage.src = ""
    imagePreview.style.display = "none"
    imageInfo.textContent = ""
  })

  function readableBytes(bytes) {
    var i = Math.floor(Math.log(bytes) / Math.log(1024)),
      sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]

    return (bytes / Math.pow(1024, 1)).toFixed(1) * 1 + " " + sizes[1]
  }
})