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)
outputImage.src = `data:image/jpeg;base64,${
base64}`
}
reader.readAsDataURL(blob)
})
.catch(error => {
console.error('Error converting image to Base64:', error)
outputImage.src = ''
})
} else {
console.error('Please enter an image URL.')
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();
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);
base.value= base64
});
});
</script>
<template>
<div class="">
<!-- Your template content here -->
<image :src="base"></image>
</div>
</template>
<style scoped lang="scss">
</style>