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

如何实现Open Seadragon当前显示图片的JPG下载功能?

实现Open Seadragon当前查看图像的JPG下载函数

针对你用Open Seadragon加载多JSON tileSources的场景,以下是两种常见需求的实现函数:

1. 下载当前视口显示区域为JPG

这个函数会导出你当前屏幕上看到的图像区域:

function downloadCurrentViewportAsJPG(viewer, filename = 'seadragon-viewport.jpg') {
  // 获取视口对应的图像坐标边界
  const viewportBounds = viewer.viewport.getBounds(true);
  // 获取当前图像的实际尺寸
  const imageItem = viewer.world.getItemAt(0);
  const imageSize = imageItem.getContentSize();
  
  // 计算导出区域的像素尺寸
  const exportWidth = viewportBounds.width * imageSize.x;
  const exportHeight = viewportBounds.height * imageSize.y;
  
  // 创建画布并设置尺寸
  const canvas = document.createElement('canvas');
  canvas.width = exportWidth;
  canvas.height = exportHeight;
  const ctx = canvas.getContext('2d');
  
  // 将视口区域绘制到画布
  viewer.drawImage(ctx, {
    x: viewportBounds.x * imageSize.x,
    y: viewportBounds.y * imageSize.y,
    width: exportWidth,
    height: exportHeight,
    destX: 0,
    destY: 0,
    destWidth: exportWidth,
    destHeight: exportHeight
  });
  
  // 生成下载链接并触发下载
  const downloadLink = document.createElement('a');
  downloadLink.href = canvas.toDataURL('image/jpeg', 0.9); // 0.9为JPG画质(0-1)
  downloadLink.download = filename;
  downloadLink.click();
  
  // 清理临时元素
  canvas.remove();
  downloadLink.remove();
}

2. 下载整个图像为JPG

如果需要导出完整的高分辨率图像,使用这个函数:

function downloadFullImageAsJPG(viewer, filename = 'seadragon-full.jpg') {
  const imageItem = viewer.world.getItemAt(0);
  const imageSize = imageItem.getContentSize();
  
  // 创建与图像尺寸一致的画布
  const canvas = document.createElement('canvas');
  canvas.width = imageSize.x;
  canvas.height = imageSize.y;
  const ctx = canvas.getContext('2d');
  
  // 绘制完整图像到画布
  viewer.drawImage(ctx, {
    x: 0,
    y: 0,
    width: imageSize.x,
    height: imageSize.y,
    destX: 0,
    destY: 0,
    destWidth: imageSize.x,
    destHeight: imageSize.y
  });
  
  // 触发下载
  const downloadLink = document.createElement('a');
  downloadLink.href = canvas.toDataURL('image/jpeg', 0.9);
  downloadLink.download = filename;
  downloadLink.click();
  
  canvas.remove();
  downloadLink.remove();
}

使用说明

  • 多图像切换场景:如果你的查看器加载了多个独立tileSources,可通过viewer.world.getItemAt(index)指定要下载的图像(index为图像序号,从0开始);若需绑定当前激活图像,可结合查看器的open事件记录当前item。
  • 跨域注意事项:如果tileSources来自外部域名,需确保目标服务器配置了CORS允许跨域访问,否则画布会被污染,无法生成下载链接。
  • 调用示例:绑定按钮点击事件触发下载
// 假设你的查看器实例为viewer
document.getElementById('download-viewport-btn').addEventListener('click', () => {
  downloadCurrentViewportAsJPG(viewer);
});

内容的提问来源于stack exchange,提问作者Laura P

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:39:06