当前位置: 首页 > news >正文

图片压缩的几种方式

// 图片压缩统一转webp格式处理 export function compressImageToWebp( file: File, options?: { maxWidth?: number; quality?: number }, callback: (file: File) => void ) { const { maxWidth = 800, quality = 0.8 } = options || {}; const reader = new FileReader(); reader.onload = e => { const img = new Image(); img.onload = () => { let { width, height } = img; if (width > maxWidth) { height = (maxWidth / width) * height; width = maxWidth; } const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); ctx?.drawImage(img, 0, 0, width, height); canvas.toBlob( blob => { if (!blob) return; const compressedFile = new File( [blob], file.name.replace(/\.(png|jpe?g)$/i, '.webp'), { type: 'image/webp', lastModified: Date.now(), } ); callback(compressedFile); }, 'image/webp', quality ); }; img.src = e.target!.result as string; }; reader.readAsDataURL(file); }
// File 类型压缩 export function compressFile(file: File, callback: Function) { const reader = new FileReader(); reader.onload = function (event: any) { const img: any = new Image(); img.onload = function () { const canvas = document.createElement("canvas"); const MAX_WIDTH = 800; const MAX_HEIGHT = 600; let width = img.width; let height = img.height; if (width > height) { if (width > MAX_WIDTH) { height *= MAX_WIDTH / width; width = MAX_WIDTH; } } else { if (height > MAX_HEIGHT) { width *= MAX_HEIGHT / height; height = MAX_HEIGHT; } } canvas.width = width; canvas.height = height; const ctx: any = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, width, height); canvas.toBlob( function (blob: any) { // 将 Blob 对象转换为 File 对象,保持原有的文件名和类型 const compressedFile = new File([blob], file.name, { type: file.type, }); callback(compressedFile); }, file.type, 0.92, ); // 质量参数,范围是 0 到 1,0.92 表示92%的质量 }; img.src = event.target.result; // 设置 img 的 src 为 FileReader 的结果,即图片的 URL }; reader.readAsDataURL(file); // 读取文件内容为 DataURL }
// base64 类型压缩 export function imageCompress(base64: string) { let Img = new Image(), dataURL = ""; Img.src = base64; let pic = new Promise(function (resolve) { Img.onload = function () { //要先确保图片完整获取到,这是个异步事件 let canvas: any = document.createElement("canvas"), //创建canvas元素 width = Img.width, //确保canvas的尺寸和图片一样 height = Img.height; // 默认将长宽设置为图片的原始长宽,这样在长宽不超过最大长度时就不需要再处理 let ratio = width / height, maxLength = 1000, newHeight = height, newWidth = width; // 在长宽超过最大长度时,按图片长宽比例等比缩小 if (width > maxLength || height > maxLength) { if (width > height) { newWidth = maxLength; newHeight = maxLength / ratio; } else { newWidth = maxLength * ratio; newHeight = maxLength; } } canvas.width = newWidth; canvas.height = newHeight; canvas.getContext("2d").drawImage(Img, 0, 0, newWidth, newHeight); //将图片绘制到canvas中 dataURL = canvas.toDataURL("image/jpeg", 0.5); //转换图片为dataURL resolve(dataURL); }; }); return pic; }
// 图片统一转webp格式来压缩 export function compressImageToWebp( file: File, callback: (file: File) => void, options?: { maxWidth?: number; maxHeight?: number; quality?: number }, ) { const { maxWidth = 2000, maxHeight = 3000, quality = 0.98 } = options || {}; const reader = new FileReader(); reader.onload = (e) => { const img = new Image(); img.onload = () => { let { width, height } = img; if (width > height) { if (width > maxWidth) { height *= maxWidth / width; width = maxWidth; } } else { if (height > maxHeight) { width *= maxHeight / height; height = maxHeight; } } const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; const ctx = canvas.getContext("2d"); ctx?.drawImage(img, 0, 0, width, height); canvas.toBlob( (blob) => { if (!blob) return; console.log("blob++++", blob); const compressedFile = new File( [blob], file.name.replace(/\.(png|jpe?g)$/i, ".webp"), { type: "image/webp", lastModified: Date.now(), }, ); callback(compressedFile); }, "image/webp", quality, ); }; img.src = e.target!.result as string; }; reader.readAsDataURL(file); }
使用成熟库 import imageCompression from "browser-image-compression"; export async function compressImage(file: any) { const options = { maxSizeMB: 5, // 目标最大体积 (MB) // maxWidthOrHeight: 1920, // 最大宽高限制 useWebWorker: true, // 启用多线程防阻塞 // fileType: "image/png", //限制上传的图片格式,这里不做限制 mimeType: "image/png", // 指定压缩后图片的格式 }; try { const blobFile = await imageCompression(file, options); const compressedFile = new File([blobFile], file.name, { type: file.type, }); return compressedFile; } catch (error) { console.error("压缩失败:", error); } }

接收处理的地方:

const compressedFiles = acceptedFiles.map((i: any, j: number) => { if (i.size > 5 * 1024 * 1024) { compressImage(i, (compressedFile: any) => { i = compressedFile; return i; }); }else{ return i; } });

let compressedFiles:any = [] for(let i = 0; i < acceptedFiles.length; i++){ if (acceptedFiles[i].size > 5 * 1024 * 1024) { // 大于5M,需要压缩 setSubmitMaterialsLoading(true); handleMyAdmToast(true, '图片压缩中'); const compressRes:any = await compressImage(acceptedFiles[i]); compressedFiles.push(compressRes) setSubmitMaterialsLoading(false); handleMyAdmToast(false); }else{ compressedFiles.push(acceptedFiles[i]) } }
http://www.jsqmd.com/news/1199176/

相关文章:

  • 【AI前沿】2026.07.16 WAIC 2026明日开幕,阶跃星辰发布全球首款AI智能体手机,Claude Code安全事件升级
  • 续电路原理图学习——晶振电路与按键电路的进阶:从独立到矩阵,再到单IO口方案
  • 2026年实测 图片转PDF哪个小程序好用 亲测有效教程 - 玩机日常
  • C++编译优化实战:从原理到工具链配置,提升开发效率与程序性能
  • Wi-Fi 串口服务器和 ZigBee 串口服务器怎么选
  • 2026 天津黄金回收,易奢福上门无服务费 - 奢侈品回收实体店
  • 2026泰州暴雨窗户飘窗渗水漏雨怎么办?专业窗边渗漏根治找宅安选房屋修缮 - 宅安选房屋修缮
  • 毕业材料一次过,pdf转换器哪个好横评这三款免费工具不踩坑 - 博客万
  • LabVIEW界面设计进阶:从扁平化到动态交互的实战指南
  • AI生成内容在社交媒体泛滥:LinkedIn长文超40%为AI创作
  • 2026年四川自驾旅行社优选参考,为你的自驾之旅保驾护航! - 企业推荐官
  • HarmonyOS掌上记账APP开发实践第12篇:@Type 装饰器 — 解决嵌套对象响应式的终极方案
  • 如何在10分钟内为Unity游戏实现实时AI翻译:XUnity.AutoTranslator终极指南
  • AD高效设计:一键导入与分类管理原理图库PCB库实战指南
  • 单片机开发中RTOS的核心机制与应用实践
  • Greenfield vs Brownfield:软件开发中的“绿地”与“棕地”项目全解析
  • TCAS安全审计终极指南:如何验证认证服务器的安全性
  • MATLAB实战:从线性规划到非线性规划,数学建模优化问题全解析
  • MetaBlriGer V2.7实战:为任意拓扑角色注入MetaHuman级面部动画
  • 2026南京LV回收怎么卖最高价?内行不亏价实操技巧指南 - 全国二奢机构参考
  • 2026杭州翡翠回收多场景服务指南:全场景适配闲置变现需求 - 奢侈品回收机构参考
  • pdf合并工具免费网页版怎么挑:零碎单据拼成整本,实测后才敢推荐的几款 - 博客万
  • 飞致云AI CRM实战:Cordys CRM×WorkBuddy赋能百人销售团队
  • Windows平台ADB环境搭建与无线调试实战指南
  • 告别“火烧验金”的野蛮生长:2026年广州黄金回收透明化流程实测与定价逻辑拆解 - 奢侈品回收评测
  • 2026连云港徐州消防通道划线厂区划线小区划线公司TOP5测评 - LYL仔仔
  • 手机号码定位终极指南:5分钟掌握开源定位工具location-to-phone-number
  • 技术选型中工具可控性为何比表面强大更重要
  • 泰州市 CPPM 培训机构怎么选|中采供培 - 中采供培
  • 骁龙移动平台双卡双待DSDS的技术内幕(7): DSDS功耗优化与DRX/eDRX策略