当前位置:网站首页>js:图片url转base64编码
js:图片url转base64编码
2022-07-23 15:33:00 【彭世瑜】
思路:
- 将图片url转为Image对象
- 将Image对象绘制到Canvas上
- 将Canvas对象转为Base64
实现代码
// Image对象转base64
function imageToBase64(image) {
let canvas = document.createElement('canvas')
let width = image.width
let height = image.height
canvas.width = width
canvas.height = height
let context = canvas.getContext('2d')
context.drawImage(image, 0, 0, width, height)
return canvas.toDataURL('image/png')
}
// 回调方式
function urlToBase64(url, callback = null) {
let image = new Image()
image.setAttribute('crossOrigin', 'Anonymous')
image.src = url + '?v=' + Math.random()
image.onload = function () {
let dataURL = imageToBase64(image)
if (callback) {
callback(dataURL)
}
}
}
// Promise方式
function urlToBase64Async(url) {
return new Promise((resolve, reject) => {
urlToBase64(url, (data) => {
resolve(data)
})
})
}
(async () => {
let image_url ='https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'
const dataURL = await urlToBase64Async(image_url)
console.log(dataURL)
// data:image/png;base64,iVBORw0KGgoAAAANSU
})()
需要注意的是:
浏览器中有跨域问题的存在,所以浏览器端处理的图片地址,需要确保允许跨域
边栏推荐
猜你喜欢

Interviewer: what is the possible reason for the slow query of MySQL database besides the index problem?

From 5 seconds to 1 second, remember the performance optimization with "very" significant effect once

基于OpenPGP的文件管理系统

ContextLoaderListener vs DispatcherServlet

idea debug常用操作

xlinx pcie xvc

作为一名后台开发人员,你必须知道的两种过滤器
![[operation] Yan Yi (Internet new technology operation)](/img/7a/38c7a9ed79e626506de067f360384c.png)
[operation] Yan Yi (Internet new technology operation)

Visualization of network infrastructure

Trust guessing numbers game
随机推荐
rust求数组中最大值
Repository XXX does not have a rease file "suggested collection"
ContextLoaderListener vs DispatcherServlet
MySQL大量写入问题优化方案 MySQL参数调优
LeetCode_724_寻找数组的中心下标
mysqldump的各项参数
LeetCode_动态规划_中等_120.三角形最小路径和
Tapdata 与优炫数据库完成产品兼容性互认证
卡方分布、方差分析
As a background developer, you must know two kinds of filters
SAP HANA数据库备份失败解决办法
[JS] check whether the date object is invalid date
分布式事务解决方案
Transfer business append log (transaction propagation behavior)
IDEA这些既好用又好玩的三十多个宝贝插件你还不知道吗?「建议收藏」
Aike AI frontier promotion (7.23)
@Will multiple bean instances be created by multiple method calls of bean annotations
RS232 DB9串口设备
Page return update
The use method of quota command is expanded in detail, and the carrying method of quota command in RHEL 7! Disk capacity quota!