1

I've tried using document.execCommand('copy') like this site but it didn't work (nothing got copied to my clipboard despite the fact that the console.log said it was successful). I also used the navigator.clipboard API but that didn't work for my jpg images, and here is its code:

navigator.clipboard.write(
[
    new ClipboardItem({
        'image/jpeg': new Blob( ['media/anime_0.jpg'],{type:'image/jpeg'} )
    })
])
.then(e=>{console.log('Copied to clipboard')})
.catch(e=>{console.log(e)})

The above code produces the following error:

DOMException: Sanitized MIME type image/jpeg not supported on write.

Anyone know if I'm doing anything wrong or if it's even possible to copy images to clipboard without using external libraries?

user8380672
  • 520
  • 1
  • 9
  • 20
  • Pretty sure the `Blob` should actually have the raw image data - potentially as loaded in via Fetch API - and not just a URL. – Niet the Dark Absol Jul 15 '20 at 07:24
  • Could you specify what you mean by "raw image data"? Would base64 / Uint8array forms of an image be considered raw image data? – user8380672 Jul 15 '20 at 07:30
  • 1
    Image to blob -> https://stackoverflow.com/questions/42471755/convert-image-into-blob-using-javascript – Keith Jul 15 '20 at 07:41

1 Answers1

5

Thanks Keith for the link to: convert image into blob using javascript

This is the solution I used for my app (it will only save images as png, as jpeg/jpg files keep giving me the DOMException error.

const img = new Image
const c = document.createElement('canvas')
const ctx = c.getContext('2d')

function setCanvasImage(path,func){
    img.onload = function(){
        c.width = this.naturalWidth
        c.height = this.naturalHeight
        ctx.drawImage(this,0,0)
        c.toBlob(blob=>{
            func(blob)
        },'image/png')
    }
    img.src = path
}

setCanvasImage('media/anime_0.jpg',(imgBlob)=>{
    console.log('doing it!')
    navigator.clipboard.write(
        [
            new ClipboardItem({'image/png': imgBlob})
        ]
    )
    .then(e=>{console.log('Image copied to clipboard')})
    .catch(e=>{console.log(e)})
})
user8380672
  • 520
  • 1
  • 9
  • 20
  • +1, writing to the canvas and extracting the PNG from there is the best path in my opinion, and should work in both Chrome and Safari (who both support PNG in navigator.clipboard). For another code example, here's the [chrome test](https://source.chromium.org/chromium/chromium/src/+/master:third_party/blink/web_tests/external/wpt/clipboard-apis/async-write-image-read-image.https.html) that shows related logic (reading/writing an image to a canvas, and reading/writing via navigator.clipboard). – Darwin Huang Aug 17 '20 at 19:19