前端 react 實現(xiàn)圖片上傳前壓縮(縮率圖)
一、安裝
npm install compressorjs 或 yarn add compressorjs
官方文檔:compressorjs - npm (npmjs.com)
二、編寫工具類
/** * @author Dragon Wu * @since 2024/8/4 12:23 * 圖片壓縮工具 */ import Compressor from 'compressorjs'; // 壓縮圖片方法 (中間件) export function compressor(file: File, defaultQuality: number = 0.6) { // console.log('壓縮前: ', (file.size / 1024 / 1024).toFixed(1), 'M');//控制臺打印圖片大小 const filesize: number = parseFloat((file.size / 1024 / 1024).toFixed(1)); let quality = defaultQuality; if (filesize < 0.8) { //這里可以設(shè)置自己的壓縮規(guī)則 quality = 1; } else if (filesize < 1) { quality = 0.8; } else if (filesize < 1.5) { quality = 0.7; } else if (filesize < 2) { quality = 0.5; } else if (filesize < 3) { quality = 0.33; } else if (filesize < 4) { quality = 0.25; } else if (filesize < 5) { quality = 0.2; } else if (filesize < 8) { quality = 0.125; } else if (filesize < 10) { quality = 0.1; } else { return new Promise((resolve, reject) => { reject({ msg: '圖片不能超過10M' }) }); } // console.log('壓縮比例: ', quality); return new Promise((resolve) => { new Compressor(file, { quality: quality, success(result: File | Blob) { // console.log('壓縮后: ', (result.size / 1024 / 1024).toFixed(1), 'M'); if (result instanceof Blob) { //@ts-ignore result = new File([result], "f" + (result?.name as string).slice(-8), {type: result.type}) } resolve(result); }, error(err) { // 壓縮報錯的話 返回原圖片 resolve(file); }, }); }); }
三、獲取壓縮后的File對象
const handleBeforeUpload = (file: FileType) => { const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'; if (!isJpgOrPng) { message.warning('只能上傳JPG/PNG格式!').then(); } const isLt2M = file.size / 1024 / 1024 < 10; if (!isLt2M) { message.warning('圖片不得超過10MB!').then(); } compressor(file).then(res => { if (isJpgOrPng && isLt2M) { onChange(res) } }) return false; }
四、測試效果
可以看到源圖片已經(jīng)被壓縮了,這樣處理后再提交至服務(wù)器就能節(jié)省帶寬,提高前端加載效率了,注意質(zhì)量數(shù)值設(shè)置的過小圖片過大可能導(dǎo)致圖片失幀。
總結(jié)到此!
到此這篇關(guān)于前端 react 實現(xiàn)圖片上傳前壓縮 縮率圖的文章就介紹到這了,更多相關(guān) react 圖片上傳前壓縮內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Axios在React中請求數(shù)據(jù)的方法詳解
這篇文章主要給大家介紹了初學(xué)React,如何規(guī)范的在react中請求數(shù)據(jù),主要介紹了使用axios進(jìn)行簡單的數(shù)據(jù)獲取,加入狀態(tài)變量,優(yōu)化交互體驗,自定義hook進(jìn)行數(shù)據(jù)獲取和使用useReducer改造請求,本文主要適合于剛接觸React的初學(xué)者以及不知道如何規(guī)范的在React中獲取數(shù)據(jù)的人2023-09-09react國際化化插件react-i18n-auto使用詳解
這篇文章主要介紹了react國際化化插件react-i18n-auto使用詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03React實現(xiàn)預(yù)覽展示docx和Excel文件
這篇文章主要為大家詳細(xì)介紹了如何使用React實現(xiàn)預(yù)覽展示docx和Excel文件,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-02-02