You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Delphi TMS WEB Core中实现TWebImageControl图片复制到剪贴板

在TMS WEB Core中复制TWebImageControl的图片到剪贴板

要实现点击按钮将TWebImageControl中的图片复制到剪贴板,需借助浏览器的Clipboard API结合Canvas完成图片格式转换,具体实现如下:

核心代码实现

在按钮的OnClick事件中添加以下逻辑:

procedure TForm1.WebButton1Click(Sender: TObject);
var
  LImgElement: TJSHTMLImageElement;
  LCanvas: TJSHTMLCanvasElement;
  LContext: TJSCanvasRenderingContext2D;
begin
  // 获取WebImageControl对应的DOM图片元素
  LImgElement := TJSHTMLImageElement(WebImageControl1.ImgElement);
  
  // 创建Canvas并绘制原图片
  LCanvas := TJSHTMLCanvasElement(document.createElement('canvas'));
  LCanvas.width := LImgElement.naturalWidth;
  LCanvas.height := LImgElement.naturalHeight;
  LContext := LCanvas.getContext('2d');
  LContext.drawImage(LImgElement, 0, 0);
  
  // 将Canvas内容转换为Blob并写入剪贴板
  LCanvas.toBlob(procedure(AImageBlob: TJSBlob)
    var
      LClipboardItem: TJSClipboardItem;
    begin
      if Assigned(AImageBlob) then
      begin
        // 创建剪贴板项(指定图片MIME类型为PNG)
        LClipboardItem := TJSClipboardItem.new(TJSObject.create('image/png', AImageBlob));
        
        // 写入剪贴板并处理结果
        navigator.clipboard.write([LClipboardItem])
          .then(procedure
            begin
              ShowMessage('图片已复制到剪贴板');
            end)
          .catch(procedure(AError: TJSObject)
            begin
              ShowMessage('复制失败:' + AError.toString);
            end);
      end;
    end, 'image/png');
end;

关键注意事项

  • 跨域图片处理:若图片来自外部域名,需先设置图片跨域属性避免Canvas污染,可在TWebImageControl的OnLoad事件中添加:
    procedure TForm1.WebImageControl1Load(Sender: TObject);
    var
      LImgElement: TJSHTMLImageElement;
    begin
      LImgElement := TJSHTMLImageElement(WebImageControl1.ImgElement);
      LImgElement.crossOrigin := 'anonymous';
    end;
    
    同时确保图片所在服务器配置了正确的CORS响应头。
  • 浏览器环境要求:Clipboard API需在HTTPS环境下使用(本地开发的localhost除外),现代主流浏览器均支持该API。

内容的提问来源于stack exchange,提问作者Shaun Roselt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 11:42:45