在线图片转Base64图片的方法

2023-12-13 03:05:03

html版(不包含跨域解决,输入在线图片地址即可转换)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image URL to Base64</title>
</head>

<body>
    <label for="inputImageUrl">Image URL:</label>
    <input type="text" id="inputImageUrl" placeholder="Enter image URL" />
    <button onclick="convertImageUrlToBase64()">Convert to Base64</button>

    <div>
        <p>Base64 encoded image:</p>
        <img id="outputImage" alt="Base64 encoded image">
    </div>

    <script>
        function convertImageUrlToBase64 () {
            const inputImageUrl = document.getElementById('inputImageUrl').value
            const outputImage = document.getElementById('outputImage')

            if (inputImageUrl) {
                fetch(inputImageUrl)
                    .then(response => response.blob())
                    .then(blob => {
                        const reader = new FileReader()
                        reader.onloadend = function () {
                            const base64 = reader.result.split(',')[1]
                            console.log('Base64 encoded image:', base64)
                            // 将Base64编码的图片展示在<img>元素上
                            outputImage.src = `data:image/jpeg;base64,${base64}`
                        }
                        reader.readAsDataURL(blob)
                    })
                    .catch(error => {
                        console.error('Error converting image to Base64:', error)
                        // 清空<img>元素的src,以便清除之前可能显示的图片
                        outputImage.src = ''
                    })
            } else {
                console.error('Please enter an image URL.')
                // 清空<img>元素的src,以便清除之前可能显示的图片
                outputImage.src = ''
            }
        }
    </script>
</body>

</html>

Vue版(包含大部分图片跨域解决,本人当初采用这个五个跨域解决了四个,只有一个没解决没转换成功)

<script setup>
    import { ref, onMounted } from 'vue';
    
    const count = ref(0);
    
    const getBase64 = (img_url) => {
      function toBase64(image) {
        const canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(image, 0, 0, image.width, image.height);
        const base64 = canvas.toDataURL('image/png');
        return base64;
      }
    
      return new Promise((resolve, reject) => {
        const image = new Image();
        image.setAttribute('crossOrigin', 'anonymous'); // 解决跨域
        image.crossOrigin = '*';
        image.src = img_url + '?v=' + Math.random(); // 解决图片URL缓存问题
        image.onload = () => {
          resolve(toBase64(image));
        };
      });
    };
    let base = ref('')
    onMounted(() => {
      getBase64(
        'http://take-saas.oss-cn-hangzhou.aliyuncs.com/wechat_applets/annual/2023/static/image/page1/bgcing.png'
      ).then(base64 => {
        console.log('Base64 encoded image:', base64);  // base64图片地址
        base.value= base64
      });
    });
    </script>
    
    <template>
      <div class="">
        <!-- Your template content here -->
        <image :src="base"></image>
      </div>
    </template>
    
    <style scoped lang="scss">
      /* Your styles here */
    </style> 

文章来源:https://blog.csdn.net/weixin_68658847/article/details/134885605
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。