Open1

JavaScript 画像をdataURLからクリップボードにコピー

3w36zj63w36zj6
console.log(imageElement)  // <img src="data:image/png;base64,...">

const base64ToBlob = (base64Data: string): Blob => {
  const contentType = "image/png"
  const sliceSize = 512
  const byteCharacters = atob(base64Data)
  const byteArrays: Uint8Array[] = []
  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize)
    const byteNumbers: number[] = new Array(slice.length)
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i)
    }
    const byteArray = new Uint8Array(byteNumbers)
    byteArrays.push(byteArray)
  }
  return new Blob(byteArrays, { type: contentType })
}

navigator.clipboard.write([
  new ClipboardItem({
    "image/png": base64ToBlob(imageElement.src.replace("data:image/png;base64,", "")),
  }),
])