当前位置:网站首页>img转base64
img转base64
2022-08-10 17:39:00 【凡小多】
img转base64
一个简单的img地址转base64格式,并可以设置压缩比例以及图片格式
// 参数说明:图片地址(本地或者线上url)、处理后返回的base64内容、指定图片类型
function imgToBase64(url, outputFormat) {
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image;
img.crossOrigin = 'Anonymous'; //解决Canvas.toDataURL 图片跨域问题
img.onload = () => {
let width = img.width;
let height = img.height;
// 压缩比例 -- 可以自己修改参数。500px宽度以下原尺寸,大于500px比例处理
let bili = Math.round(width / 500) || 1;
let rate = 1 / bili;
canvas.width = width * rate;
canvas.height = height * rate;
ctx.drawImage(img, 0, 0, width, height, 0, 0, width * rate, height * rate);
let dataURL = canvas.toDataURL(outputFormat || 'image/jpeg');
// 去除标头 -- 传递给后台时一般去除头部
// let reg = new RegExp('^data:image/[^;]+;base64,');
// dataURL = dataURL.replace(reg, '');
canvas = null;
resolve(dataURL);
}
img.src = url;
})
};
// 调用:
imgToBase64("https://img0.bdstatic.com/static/searchdetail/img/logo-2X_2dd9a28.png").then(res => console.log(res))
边栏推荐
- Interpretation of ZLMediaKit server source code---RTSP push and pull
- Selenium - 如何使用隐式、显示、强制元素等待?
- 机器人控制器编程实践指导书旧版-实践六 LCD液晶显示(点阵)
- ARM开发(三)ARM寻址方式,异常中断,异常向量表
- shopee API 接入说明
- 测试接口出现“data“: “Full authentication is required to access this resource“凭证已过期
- DASCTF2022.07 empowerment competition WEB topic recurrence
- 本周四晚19:00知识赋能第六期第5课丨OpenHarmony WiFi子系统
- 讯飞翻译机抢镜背后,跨语种沟通迈入全新时代
- FFmpeg Huaping solution (modify source code, discard incomplete frames)
猜你喜欢

redis分布式锁

机器人控制器编程实践指导书旧版-实践四 步进电机(执行器)

五菱宏光MINI EV,唯一的缺点就是安全性

Before opening a futures account, you must confirm the handling fee as soon as possible

Return the next higher prime number

Toronto Research Chemicals 双(乙酰丙酮)铂(II)

烟雾、空气质量、温湿度…自己徒手做个环境检测设备

Toronto Research Chemicals霉菌毒素分析丨T2 四醇

本周四晚19:00知识赋能第六期第5课丨OpenHarmony WiFi子系统

Go-Excelize API源码阅读(六)—— DeleteSheet(sheet string)
随机推荐
Toronto Research Chemicals农药检测丨甲硫威
Toronto Research Chemicals萜烯分析丨反式植物醇
基于AWS构建云上数仓第二步:AWS常见服务简介
讯飞翻译机抢镜背后,跨语种沟通迈入全新时代
强网杯2021final
Error creating bean with name ‘sqlSessionFactory‘ defined in class path reso「建议收藏」
同一块中出现两个 * 就不能正常显示
pip install fatal error C1083 cannot open include file "io.h" No such file or directory
oracle11g体系结构
本周四晚19:00知识赋能第六期第5课丨OpenHarmony WiFi子系统
CAS客户端对接
AVFrame related api memory management
兼具外观、性能、屏幕!华硕灵耀X 14火热抢购中
【Web3 系列开发教程——创建你的第一个 NFT(8)】如何开发一个成功的 NFT 项目 | NFT 社区建设技巧
不止跑路,拯救误操作rm -rf /*的小伙儿
「业务架构」业务能力的热图是什么,有啥用?
JNDI and RMI, LDAP
施工企业数字化转型解决方案设计思路
迪文发布新款2K高清DGUS智能屏
Return the next higher prime number