背景
- 一般图片以png或者jpg等为后缀,但tif的图片无法通过img src直接预览,本文将阐述如何实现tif图片预览
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.img-box {
max-width: 1200px;
margin: 0 auto;
}
.img-box img {
width: 100%;
}
</style>
</head>
<body>
<div class="img-box">
<img id="img" src="" />
</div>
</body>
<script src="./tiff.min.js"></script>
<script src="./1.js"></script>
<script>
const img = document.getElementById("img")
// 得到base64,转成文件,然后文件读取成tiff arraybuffer
function dataURLtoBlob(dataurl) {
const arr = dataurl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
const file = dataURLtoBlob(base64text);
file.arrayBuffer().then(arrayBuffer => {
const tiff = new Tiff({ buffer: arrayBuffer })
const imgData = tiff.toDataURL() // 使用base64调此方法
img.src = imgData
})
</script>
</html>
1.js里面的文件为tif的图片转为了base64. 2. tiff为第三方库,用于转化图片
下面为codesandbox的链接。 codesandbox.io/s/suspiciou…
后端返回数据流处理
requestApi().then((res) => {
const img = document.getElementById('test');
res.blob().then((blob) => {
blob.arrayBuffer().then((arrayBuffer) => {
// eslint-disable-next-line no-undef
const tiff = new Tiff({ buffer: arrayBuffer });
const imgData = tiff.toDataURL(); // 使用base64调此方法
img.src = imgData;
})
});
})