vue中显示 .tif 图片

1、安装 tiff

cnpm install tiff.js

2、main.js 引入

import Tiff from 'tiff.js';
<template>
	<canvas id="tiff-canvas" style="width: 200px; height: auto;"></canvas>
</template>
<script>
export default {
	mounted(){
	 this.renderTiffImage('aaa.tif', 'tiff-canvas');
	}

	methods:{
	    // 渲染 TIFF 图像到 Canvas
	    renderTiffImage(tiffUrl, canvasId) {
	        // 获取 Canvas 元素
	        const canvas = document.getElementById(canvasId);
	        if (!canvas) return;
	        // 获取 Canvas 的显示尺寸
	        const canvasWidth = 1400;  // Canvas 显示的宽度
	        const canvasHeight = 1000;  // Canvas 显示的高度
	        // 计算设备的像素比率
	        const dpr = window.devicePixelRatio || 1;
	        // 设置 Canvas 的物理大小
	        canvas.width = canvasWidth * dpr;
	        canvas.height = canvasHeight * dpr;
	        // 创建一个 XMLHttpRequest 请求来加载 TIFF 文件
	        const xhr = new XMLHttpRequest();
	        xhr.open('GET', tiffUrl, true);
	        xhr.responseType = 'arraybuffer'; // 设置响应类型为二进制
	        // 当请求成功时,使用 tiff.js 解析 TIFF 文件
	        xhr.onload = () => {
	            const arrayBuffer = xhr.response;
	            const tiff = new Tiff({ buffer: arrayBuffer }); // 使用 tiff.js 解析 TIFF 文件
	            const image = tiff.toCanvas(); // 获取 Canvas 对象
	            // 获取 TIFF 图像的原始尺寸
	            const imgWidth = image.width;
	            const imgHeight = image.height;
	            // 计算等比例缩放的宽高
	            let drawWidth, drawHeight;
	            const imgRatio = imgWidth / imgHeight;
	            const canvasRatio = canvasWidth / canvasHeight;
	            if (imgRatio > canvasRatio) {
	                // 图片更宽,宽度填满 canvas
	                drawWidth = canvasWidth * dpr;
	                drawHeight = drawWidth / imgRatio;
	            } else {
	                // 图片更高,高度填满 canvas
	                drawHeight = canvasHeight * dpr;
	                drawWidth = drawHeight * imgRatio;
	            }
	
	            // 计算图片绘制的起始位置(居中显示)
	            const offsetX = (canvas.width - drawWidth) / 2;
	            const offsetY = (canvas.height - drawHeight) / 2;
	
	            // 获取 Canvas 的上下文,并将图像绘制到 Canvas 上
	            const ctx = canvas.getContext('2d');
	            ctx.clearRect(0, 0, canvas.width, canvas.height);  // 清空 canvas
	            ctx.drawImage(image, offsetX, offsetY, drawWidth, drawHeight);
	        };
	
	        xhr.send(); // 发送请求
	    },
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值