Copy Image to Clipboard

JavaScript: copy text AND image to clipboard

You can do this by combining the execCommand and Range/Selection functionality:

let button = document.querySelector('#copy-button');

button.addEventListener('click', function () {
let selection = window.getSelection();
let container = document.querySelector('.container');

if (selection.rangeCount > 0) {
selection.removeAllRanges();
}

const range = document.createRange();
range.selectNode(container);
selection.addRange(range);
document.execCommand("copy");
selection.removeAllRanges();
});
.container {
position: relative;
text-align: center;
color: white;
}

.bottom-left {
position: absolute;
bottom: 8px;
left: 16px;
}

.top-left {
position: absolute;
top: 8px;
left: 16px;
}

.top-right {
position: absolute;
top: 8px;
right: 16px;
}

.bottom-right {
position: absolute;
bottom: 8px;
right: 16px;
}

.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<button id="copy-button">copy</button>
<div class="container">
<img src="https://moview.nl/wp-content/uploads/2018/04/Mountain_RvB-3-bw.jpg" alt="Snow" style="width:100%;">
<div class="bottom-left">Bottom Left</div>
<div class="top-left">Top Left</div>
<div class="top-right">Top Right</div>
<div class="bottom-right">Bottom Right</div>
<div class="centered">Centered</div>
</div>

Is there any way to copy image to clipboard with pure javascript without libraries?

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)})
})

Get image (using paste) from the browser

You can access it from the paste ClipboardEvent's .clipboardData DataTransfer.

It will be in the .files FileList if available:

document.onpaste = (evt) => {  const dT = evt.clipboardData || window.clipboardData;  const file = dT.files[ 0 ];  console.log( file );};
img{ height: 100vh; }
<div contenteditable>You can paste the image here</div><figure>  <figcaption>Copy this image</figcaption>  <img src="https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"></figure>

Copy image to clipboard using JavaScript

If you are trying to fetch an image from a domain you don't control, you will need to implement some server-side code to fetch the image to your domain to avoid cross-origin issues. If you will be fetching the image from a domain you control, you need to serve the images with the CORS header. Access-Control-Allow-Origin: * or Access-Control-Allow-Origin: https://domain-you-are-fetching-from.example.

Edit:
If you are using existing data URIs, you can convert them to blobs without using fetch. See Blob from DataURL?

You could also load the data URI in an image element, write that image to a canvas, and use the canvas.toBlob() method to produce a blob.

const image = document.getElementsByTagName('img')[0]image.addEventListener('click', e => {  const canvas = document.createElement('canvas')  canvas.width = image.naturalWidth  canvas.height = image.naturalHeight  const context = canvas.getContext('2d')  context.drawImage(image, 0, 0)  canvas.toBlob(blob => {    navigator.clipboard.write([      new ClipboardItem({        [blob.type]: blob      })    ]).then(() => {      console.log('Copied')    })  })})
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport" content="width=device-width, initial-scale=1.0">  <title>Document</title></head><body>  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z/C/HgAGgwJ/lK3Q6wAAAABJRU5ErkJggg==" width="20" alt="Sample Image"></body></html>

Copy image to clipboard and preserve transparency

After I found out my original answer doesn't work for most images, I did some research and constructed a working solution. Unfortunately, it has a few drawbacks:

  • It may not work for all apps (it does work for Discord, though).
  • It can't be used to copy images from memory, only from an existing file.
  • It is definitely not cross-platform (I doubt it works on older versions of Windows, even. It seems to work fine on Windows 10, at least).

The solution utilizes pywin32 and is as follows:

import os
import win32clipboard as clp

file_path = 'test.png'

clp.OpenClipboard()
clp.EmptyClipboard()

# This works for Discord, but not for Paint.NET:
wide_path = os.path.abspath(file_path).encode('utf-16-le') + b'\0'
clp.SetClipboardData(clp.RegisterClipboardFormat('FileNameW'), wide_path)

# This works for Paint.NET, but not for Discord:
file = open(file_path, 'rb')
clp.SetClipboardData(clp.RegisterClipboardFormat('image/png'), file.read())

clp.CloseClipboard()

Copy image to clipboard?

I did copy the code and replace the StringIO with BytesIO and it worked! (with *.jpg and *.png files) Thank you so much!

from io import BytesIO
import win32clipboard
from PIL import Image

def send_to_clipboard(clip_type, data):
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(clip_type, data)
win32clipboard.CloseClipboard()

filepath = 'Ico2.png'
image = Image.open(filepath)

output = BytesIO()
image.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()

send_to_clipboard(win32clipboard.CF_DIB, data)


Related Topics



Leave a reply



Submit