<template>
<div class="wrap">
<div>将图片切成方形并返回base64,将base64转成blob,将blob转成file</div>
<canvas class="my-canvas" id="myCanvas"></canvas>
<br>
<van-image :src="resImg" style="width: 200px;height: 200px;"></van-image>
<van-button @click="testFn">点我测试</van-button>
</div>
</template>
<script setup>
import { onMounted,ref } from 'vue';
const resImg = ref('')
const testFn = async()=>{
let imgUrl ='https://fat-oss-all-q.chuangzuomao.cn/20231018/user/avatar/P8AdBMBhQnwAfm2n7HA7frTRPRkPZkz51697624124994.png'
let base64Img = await clipPicToSquare(imgUrl) //图片转成base64
resImg.value = base64Img
let blob = dataURLtoBlob(base64Img); //base64转换为blob
let newfile = blobToFile(blob, 'imgName.png'); //将blob转换为file
console.log(newfile)
}
// 切图到方形 返回base64
const clipPicToSquare = (imgUrl)=>{
return new Promise((resolve,reject)=>{
let myCanvas = document.getElementById('myCanvas')
let ctx = myCanvas.getContext('2d')
let img = new Image()
img.crossOrigin = "anonymous"
img.src = imgUrl
img.onload = ()=>{
let imgWidth = img.width
let imgHeight = img.height
let clipX = 0
let clipY = 0
if(imgWidth>=imgHeight){
myCanvas.width = imgHeight
myCanvas.height = imgHeight
clipX = (imgWidth-imgHeight)/2
clipY = 0
ctx.drawImage(img,clipX,clipY,imgHeight,imgHeight,0,0,imgHeight,imgHeight)
}else{
myCanvas.width = imgWidth
myCanvas.height = imgWidth
clipX = 0
clipY = (imgHeight-imgWidth)/2
ctx.drawImage(img,clipX,clipY,imgWidth,imgWidth,0,0,imgWidth,imgWidth)
}
let resBase64 = myCanvas.toDataURL('image/png');
resolve(resBase64)
}
img.onerror = ()=>{
reject('图片加载错误')
}
})
}
//将base64转换为blob
const dataURLtoBlob = (dataurl)=> {
var arr = dataurl.split(','),mime = arr[0].match(/:(.*?);/)[1],bstr = atob(arr[1]),n = bstr.length,u8arr = new Uint8Array(n);
while (n--) {u8arr[n] = bstr.charCodeAt(n);}
return new Blob([u8arr], { type: mime });}
//将blob转换为file
const blobToFile=(theBlob, fileName)=>{
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
}
</script>
<style lang="scss" scoped>
.my-canvas{
background: rgba(255, 0, 0, 0.312);
}
</style>
vue3 将图片切成方形并返回base64,将base64转成blob,将blob转成file
最新推荐文章于 2024-05-21 15:26:24 发布