什么是tiff
tiff是一种图片的格式
今天突然看到有一个图片加载失败,控制台调出来一看,有图片地址,tiff格式的。
于是就百度查/问朋友,最后查到了一个tiff.js的文件
npm 安装 照着别人的教程来并不行,接下来,记录记录我显示tiff的过程
1.安装 命令如下
npm install --save tiff.js
- 引入tiff
var Tiff = require('tiff.js')
- 使用 图片不能返回地址,需要后台返回base64的文件流, 我从后台获取的文件流,并处理的js,完整代码,最下方
// w 为图片的宽度 h为图片的高度,设置顶比例缩放需要使用的
getImg({
responseType: 'json',
source: url
}).then(res => {
var buffer = decodeBase64(res)
var tiff = new Tiff({ buffer: buffer })
var canvas = tiff.toCanvas()
var width = tiff.width()
var height = tiff.height()
if (canvas) {
// 设置宽高 width: 560px; height: 300px; 等比例缩放图片
var scale = 1;
if (width > w || height > h) {
if (width > height) {
scale = w / width;
}else {
scale = h / height;
}
}
canvas.setAttribute('style', 'width:' + (width * scale) +
'px; height: ' + (height * scale) + 'px');
// 将处理好的图像放到指定的元素中
document.getElementById(`canvas`).append(canvas)
}
}
// 将base64转码 为tiff.js需要的格式
decodeBase64 (base64Str) {
var bString = atob(base64Str)
var len = bString.length
var arr = new Uint8Array(len)
while (len--) {
arr[len] = bString.charCodeAt(len)
}
return arr
}
我将这些抽取出来整合js文件,在后面需要使用的页面直接引入,现在奉上完整代码 filterTiff.js
// filterTiff.js
import { getImg } from '@/api/water'
var Tiff = require('tiff.js')
/**
* 将tiff文件转化
* @param {String} 文件名 目标文件地址
* @param {String} filename 想要保存的文件名称
*/
function getTif({url, w, h}) {
return new Promise((resolve, reject) => {
getImg({
responseType: 'json',
source: url
}).then(res => {
var buffer = decodeBase64(res)
var tiff = new Tiff({ buffer: buffer })
var canvas = tiff.toCanvas()
var width = tiff.width()
var height = tiff.height()
if (canvas) {
// 设置宽高 width: 560px; height: 300px; 等比例缩放图片
var scale = 1;
if (width > w || height > h) {
if (width > height) {
scale = w / width;
}else {
scale = h / height;
}
}
canvas.setAttribute('style', 'width:' + (width * scale) +
'px; height: ' + (height * scale) + 'px');
resolve(canvas)
} else {
resolve()
}
}).catch((error) => {
reject(error)
})
})
}
function decodeBase64 (base64Str) {
var bString = atob(base64Str)
var len = bString.length
var arr = new Uint8Array(len)
while (len--) {
arr[len] = bString.charCodeAt(len)
}
return arr
}
function hasTiff (url) {
let flag = false
if (url) {
let arr = url.split('.')
let str = arr[arr.length - 1]
if (str == 'tif' || str == 'tiff') {
flag = true
}
}
return flag
}
export {hasTiff, getTif}
页面中调用
<template>
<div class="detail">
<div id="canvas"></div>
</div>
</template>
<script>
import { hasTiff, getTif } from '@/utils/filterTiff.js';
export default {
methods: {
setTif ({canvas}) {
document.getElementById(`canvas`).append(canvas)
},
getDetail () {
getPictureById({
id: this.currentItem.id
}).then(res => {
if (res.code === 200) {
if (res.data && res.data) {
this.urls = res.data
hasTiff(this.urls)
this.$nextTick(() => {
getTif({url: element.url, w: 560, h: 300}).then(res => {
if (res) {
this.setTif({canvas: res})
}
})
})
} else {
this.urls = ''
}
}
})
}
}
}
</script>
网友评论