Javascript 将图像复制到剪贴板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33175909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copy image to clipboard
提问by rachedbchir
Seemingly, you can't (yet) programmatically copy an image to the clipboard from a JavaScript web app?
看起来,您(还)不能以编程方式将图像从 JavaScript Web 应用程序复制到剪贴板?
I have tried to copy a text in clipboard , and it's worked.
我试图复制剪贴板中的文本,并且成功了。
Now I would like to copy an image and after I press ctrl+vto paste into Word or Excel or Paint.
现在我想复制一个图像,然后按ctrl+v粘贴到 Word、Excel 或 Paint 中。
$(function() {
$("#btnSave").click(function() {
html2canvas($("#container1"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
Canvas2Image.saveAsPNG(canvas);
$("#img-out").append(canvas);
}
});
});
});
回答by owaisafaq
I searched the internet and couldn't find a solution to this so I went ahead and experimented. Successfully worked across all browsers:
我在互联网上搜索并找不到解决方案,所以我继续尝试。成功在所有浏览器上工作:
The HTML I'm using for testing is:
我用于测试的 HTML 是:
<div class="copyable">
<img src="images/sherlock.jpg" alt="Copy Image to Clipboard via Javascript."/>
</div>
<div class="copyable">
<img src="images/stark.jpg" alt="Copy Image to Clipboard via Javascript."/>
</div>
The JavaScript/jQuery Code looks like this:
JavaScript/jQuery 代码如下所示:
<script>
//Cross-browser function to select content
function SelectText(element) {
var doc = document;
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
}
$(".copyable").click(function (e) {
//Make the container Div contenteditable
$(this).attr("contenteditable", true);
//Select the image
SelectText($(this).get(0));
//Execute copy Command
//Note: This will ONLY work directly inside a click listenner
document.execCommand('copy');
//Unselect the content
window.getSelection().removeAllRanges();
//Make the container Div uneditable again
$(this).removeAttr("contenteditable");
//Success!!
alert("image copied!");
});
</script>
Have uploaded on GITHub as well: https://github.com/owaisafaq/copier-js
也上传到了 GITHub:https: //github.com/owaisafaq/copier-js
回答by notsiddhartha
You are right. There is no support to copy image data into clipboard in chrome yet. https://bugs.chromium.org/p/chromium/issues/detail?id=150835. Looks like it has been open for about 4 years now.
你是对的。尚不支持在 chrome 中将图像数据复制到剪贴板。https://bugs.chromium.org/p/chromium/issues/detail?id=150835。好像开了快4年了。
There is a clipboard API spec that is coming up though https://w3c.github.io/clipboard-apis/
有一个剪贴板 API 规范即将推出 https://w3c.github.io/clipboard-apis/
回答by withybetwixtye
For those still looking, the ClipboardAPI now works with png images.
对于那些仍在寻找的人,ClipboardAPI 现在可以处理 png 图像。
try {
navigator.clipboard.write([
new ClipboardItem({
'image/png': pngImageBlob
})
]);
} catch (error) {
console.error(error);
}
回答by Konstantinos
So, i created the perfect solution with 1 liner-kinda solution to convert something with html2canvas to a canvas and then produce the image of it and then save it to clipboard as png. For example,
因此,我使用 1 liner-kinda 解决方案创建了完美的解决方案,将带有 html2canvas 的内容转换为画布,然后生成它的图像,然后将其作为 png 保存到剪贴板。例如,
HTML:<div id="copyToImage">Hello World!</div>
HTML:<div id="copyToImage">Hello World!</div>
JavaScript:
JavaScript:
$("#copyToImage").click(function() {
html2canvas(document.querySelector("#copyToImage")).then(canvas => canvas.toBlob(blob => navigator.clipboard.write([new ClipboardItem({'image/png': blob})])));
});
回答by SysEng
Well, this is my first post in here with an answer i guess :)
好吧,这是我在这里的第一篇文章,我想有一个答案:)
Actually i'm currently using cefsharp web browser component one of my project, cefsharp run on chrome based browser and i want to copy img element one of webpage
实际上,我目前正在使用我的项目之一的 cefsharp 网络浏览器组件,cefsharp 在基于 chrome 的浏览器上运行,我想复制网页的 img 元素之一
With cefsharp you can manipulate browser only javascript, so i think we can handle it with using canvas element.
使用cefsharp,您只能操作浏览器javascript,所以我认为我们可以使用canvas 元素来处理它。
/*
'cause of lorempixel timeout, i used img onload function.
*/
function copyImage() {
var imgCap = document.getElementById('imgCap');
var imgCanvas = document.createElement('canvas');
imgCanvas.id = 'imgCanvas';
imgCanvas.height = 40;
imgCanvas.width = 120;
document.body.appendChild(imgCanvas);
var originalContext = imgCanvas.getContext('2d');
originalContext.drawImage(imgCap, 0, 0);
//return imgCanvas.toDataURL();
}
//document.onload = copyImage();
<img id="imgCap" src="http://lorempixel.com/120/40" onload="copyImage();"/>
with return imgCanvas.toDataURL();
you can get base64 encoded value and use wherever you want.
与return imgCanvas.toDataURL();
你能得到base64编码的价值和使用,无论你想。
this is my cefsharp code, it's working.
这是我的 cefsharp 代码,它正在工作。
string copyImageOtClipboardScript = "(function(){ try{var imgCap = document.getElementById('imgCap'); var imgCanvas = document.createElement('canvas'); imgCanvas.id = 'imgCanvas'; imgCanvas.height = 40; imgCanvas.width = 120; document.body.appendChild(imgCanvas); var originalContext = imgCanvas.getContext('2d'); originalContext.drawImage(imgCap, 0, 0); return imgCanvas.toDataURL(); }catch(e){ alert(e); } })();";
var task = chromeBrowser.EvaluateScriptAsync(copyImageOtClipboardScript).ContinueWith(x =>
{
var resp = x.Result;
if (resp.Success)
{
this.Invoke((MethodInvoker)delegate
{
Bitmap bmp = null;
string captchaResult = "", captchaBase64;
var bytes = Convert.FromBase64String(resp.Result.ToString().Replace("data:image/png;base64,", ""));
using (var imageFile = new FileStream("temp_captcha.png", FileMode.Create))
{
imageFile.Write(bytes, 0, bytes.Length);
imageFile.Flush();
}
});
}
});
回答by OverlappingElvis
Check out this guide to copying and pasting with JavaScript: https://www.lucidchart.com/techblog/2014/12/02/definitive-guide-copying-pasting-javascript/
查看此使用 JavaScript 复制和粘贴的指南:https: //www.lucidchart.com/techblog/2014/12/02/definitive-guide-copying-pasting-javascript/
According to this, Chrome, Safari, and Firefox all support copying images along with plain text, while IE only allows copying text. The page linked above describes how this service uses an extension to add this functionality to a context menu, but it appears that several browsers support programmatic copying of images.
据此,Chrome、Safari 和 Firefox 都支持复制图片和纯文本,而 IE 只允许复制文本。上面链接的页面描述了该服务如何使用扩展将此功能添加到上下文菜单中,但似乎有几个浏览器支持图像的编程复制。
回答by Casey
You cannot copy to clip board with Javascript for security reasons, a work around can be found in a discussion here. Involves flash.Click button copy to clipboard using jQuery
出于安全原因,您不能使用 Javascript 复制到剪贴板,可以在此处的讨论中找到解决方法。涉及闪光灯。使用 jQuery 单击按钮复制到剪贴板