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