在线图片转Base64图片的方法

51 篇文章 4 订阅

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>

第二种方法

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

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

<body style="background-color: red;">
  <img src="./src/assets/image/group.png" style="width: 300px;height: 300px;" alt="">

  <script>
    async function fetchAndConvertToBase64 (imageUrl) {
      try {
        const response = await fetch(imageUrl)
        const blob = await response.blob()

        return new Promise((resolve, reject) => {
          const reader = new FileReader()
          reader.onloadend = () => resolve(reader.result)
          reader.onerror = reject
          reader.readAsDataURL(blob)
        })
      } catch (error) {
        console.error('Error fetching or converting the image:', error)
        throw error // Re-throw the error if needed
      }
    }

    // Example usage
    const imageUrl = 'http://take-saas.oss-cn-hangzhou.aliyuncs.com/icon/5cfc0fc7-def4-4342-bb0a-ee3fe650ae22.png'
    fetchAndConvertToBase64(imageUrl)
      .then(base64 => {
        console.log('Base64:', base64)
        // Do something with the base64-encoded image
      })
      .catch(error => {
        console.error('Error:', error)
        // Handle error
      });

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

封装方法
新建base.js,放入以下方法

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));
    };
  });
};

export default {
  getBase64
}

在组件内导入

import base from './base'
// 使用
let url = ''
async function base64(){
	url = await base.getBase64("http://take-saas.oss-cn-hangzhou.aliyuncs.com/wechat_applets/annual/2023/static/image/page1/bgcing.png")
	//打印
	console.log(url)
}
  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萧寂173

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值