JS通过指定大小来压缩图片
安装:
npm i image-conversion --save
引入:
<script src="https://cdn.jsdelivr.net/gh/WangYuLue/image-conversion/build/conversion.js"></script>
or
const imageConversion = require("image-conversion")
用例:
<input id="demo" type="file" onchange="view()">
一、将图像压缩到200kb
function view(){ const file = document.getElementById('demo').files[0]; console.log(file); imageConversion.compressAccurately(file,200).then(res=>{ //The res in the promise is a compressed Blob type (which can be treated as a File type) file; console.log(res); }) } // or use an async function async function view() { const file = document.getElementById('demo').files[0]; console.log(file); const res = await imageConversion.compressAccurately(file,200) console.log(res); }
二、图像精度0.9
function view(){ const file = document.getElementById('demo').files[0]; console.log(file); imageConversion.compress(file,0.9).then(res=>{ console.log(res); }) }
imageConversion的一些方法:
①imagetoCanvas()----缩放和旋转图片
例子:
imageConversion.imagetoCanvas(image); //or imageConversion.imagetoCanvas(image,{ width: 300, //result image's width height: 200, //result image's height orientation:2,//image rotation direction scale: 0.5, //the zoom ratio relative to the original image, range 0-10; //Setting config.scale will override the settings of //config.width and config.height; })
②dataURLtoFile()----确定转换后的图像类型:“Image/png”、“Image/jpeg”、“Image/gif”
③compress()----如果传入的是数字,表示图片质量;如果传入的是对象,表示将参数传递给
imagetoCanvas
和dataURLtoFile
方法
例子:
// number imageConversion.compress(file,0.8) //or // object imageConversion.compress(file,{ quality: 0.8, type: "image/jpeg",//如果压缩PNG透明图像,请选择“Image/png”类型 width: 300, height: 200, orientation:2, scale: 0.5, })
④compressAccurately()----如果是传入的是数字,表示指定压缩后图像的大小(KB);如果传入的是对象,表示将参数传递给
imagetoCanvas
和dataURLtoFile
方法
例子:
// number imageConversion.compressAccurately(file,100); //The compressed image size is 100kb // object imageConversion.compressAccurately(file,{ size: 100, //The compressed image size is 100kb accuracy: 0.9,//the accuracy of image compression size,range 0.8-0.99,default 0.95; //this means if the picture size is set to 1000Kb and the //accuracy is 0.9, the image with the compression result //of 900Kb-1100Kb is considered acceptable; type: "image/jpeg", width: 300, height: 200, orientation:2, scale: 0.5, })
参考:GitHub
图片转换工具:http://www.wangyulue.com/assets/image-comversion/example/index.html
分类:
js
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结