vue3 将图片切成方形并返回base64,将base64转成blob,将blob转成file

<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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值