<template>
    <div class="image-container">
        <img :src="base64Url" alt="">
    </div>
</template>

<script lang="ts" setup>

import {ref,defineProps} from 'vue';

const props = defineProps({
    url:String
})

const base64Url = ref<String>("")


function ImageToBase64(url){
    return new Promise(function(resolve,reject){
    let img = new Image();
    img.crossOrigin = 'Anonymous';
    img.src=url;
    try{
        img.onload = function(){
        let canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;
        let ctx = canvas.getContext('2d');
        ctx?.drawImage(img, 0, 0);
        let dataURL = canvas.toDataURL('image/jpeg'); // 或者使用 'image/jpeg' 来获得 JPEG 格式的 base64 字符串
        resolve(dataURL);
        }
    }catch(e){
        reject("NO");
    }
    })
}

ImageToBase64(props.url).then(res=>{
    base64Url.value = res.toString();
})

</script>

<style type="less" scoped>
.image-container{
    width:100%;
    height:100%;
    img {
        width:100%;
        height:100%;
    }
}
</style>