当前位置:网站首页>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
})()
需要注意的是:
浏览器中有跨域问题的存在,所以浏览器端处理的图片地址,需要确保允许跨域
边栏推荐
- Tampermonkey究竟有什么用?
- xlinx pcie xvc
- Single cell literature learning (part6) -- forestfireclustering for SC sequencing combinations iterative label promotion with
- Start multiple redis instances on a Linux machine
- Leetcode skimming: dynamic planning 04 (different paths)
- rust求两数之和
- Interviewer: how to use redis to realize distributed locks?
- LeetCode_455_分发饼干
- Do you really understand the persistence mechanism of redis?
- MySQL六十六问,两万字+五十图详解含(答案解析)
猜你喜欢
随机推荐
Trust guessing numbers game
基于OpenPGP的文件管理系统
TwinCAT 3 首次运行报错4115
LeetCode_ 455_ Distribute cookies
isEmpty 和 isBlank 的用法区别,至少一半的人答不上来...
Keras之二分类问题
PDO操作
rust统计文件中单词出现的次数
多线程编程
(十一)STM32——IO引脚复用与映射
MYSQL基础及性能优化
卡方分布、方差分析
Record the range of data that MySQL update will lock
MySQL执行Alter table xx add column报Duplicate entry错误
LQR control learning -lqr control matlab official tutorial -lqr controller_ Modeling and analysis of state space system with matlab/simulink
训练和测试的loss不下降,并且精度超低
工业物联网中的时序数据
From Markov chain to GPT, Li Hang, director of ByteDance AI Lab, detailed the past and present lives of language models
c语言--通讯录的实现与ScreenToGif
Kv260 single board PS control setting IIC switch chip








