在網頁瀏覽器中運行的 Javascript 模組用於圖像壓縮。
開啟 https://donaldcwl.github.io/browser-image-compression/example/basic.html
或檢查此儲存庫中的“example”資料夾
< input type =" file " accept =" image/* " onchange =" handleImageUpload(event); " >
async function handleImageUpload ( event ) {
const imageFile = event . target . files [ 0 ] ;
console . log ( 'originalFile instanceof Blob' , imageFile instanceof Blob ) ; // true
console . log ( `originalFile size ${ imageFile . size / 1024 / 1024 } MB` ) ;
const options = {
maxSizeMB : 1 ,
maxWidthOrHeight : 1920 ,
useWebWorker : true ,
}
try {
const compressedFile = await imageCompression ( imageFile , options ) ;
console . log ( 'compressedFile instanceof Blob' , compressedFile instanceof Blob ) ; // true
console . log ( `compressedFile size ${ compressedFile . size / 1024 / 1024 } MB` ) ; // smaller than maxSizeMB
await uploadToServer ( compressedFile ) ; // write your own logic
} catch ( error ) {
console . log ( error ) ;
}
}
function handleImageUpload ( event ) {
var imageFile = event . target . files [ 0 ] ;
console . log ( 'originalFile instanceof Blob' , imageFile instanceof Blob ) ; // true
console . log ( `originalFile size ${ imageFile . size / 1024 / 1024 } MB` ) ;
var options = {
maxSizeMB : 1 ,
maxWidthOrHeight : 1920 ,
useWebWorker : true
}
imageCompression ( imageFile , options )
. then ( function ( compressedFile ) {
console . log ( 'compressedFile instanceof Blob' , compressedFile instanceof Blob ) ; // true
console . log ( `compressedFile size ${ compressedFile . size / 1024 / 1024 } MB` ) ; // smaller than maxSizeMB
return uploadToServer ( compressedFile ) ; // write your own logic
} )
. catch ( function ( error ) {
console . log ( error . message ) ;
} ) ;
}
您可以透過npm或yarn安裝它
npm install browser-image-compression --save
# or
yarn add browser-image-compression
import imageCompression from 'browser-image-compression' ;
(可用於 React、Angular、Vue 等框架)
(與 webpack 和 rollup 等捆綁器一起使用)
您可以從 dist 資料夾下載 imageCompression。
或者,您可以使用像 delivrjs 這樣的 CDN:
< script type =" text/javascript " src =" https://cdn.jsdelivr.net/npm/[email protected]/dist/browser-image-compression.js " > </ script >
如果這個專案可以幫助你減少開發時間,你可以請我一杯咖啡:)
(由條紋提供支撐)
// you should provide one of maxSizeMB, maxWidthOrHeight in the options
const options : Options = {
maxSizeMB : number , // (default: Number.POSITIVE_INFINITY)
maxWidthOrHeight : number , // compressedFile will scale down by ratio to a point that width or height is smaller than maxWidthOrHeight (default: undefined)
// but, automatically reduce the size to smaller than the maximum Canvas size supported by each browser.
// Please check the Caveat part for details.
onProgress : Function , // optional, a function takes one progress argument (percentage from 0 to 100)
useWebWorker : boolean , // optional, use multi-thread web worker, fallback to run in main-thread (default: true)
libURL : string , // optional, the libURL of this library for importing script in Web Worker (default: https://cdn.jsdelivr.net/npm/browser-image-compression/dist/browser-image-compression.js)
preserveExif : boolean , // optional, use preserve Exif metadata for JPEG image e.g., Camera model, Focal length, etc (default: false)
signal : AbortSignal , // optional, to abort / cancel the compression
// following options are for advanced users
maxIteration : number , // optional, max number of iteration to compress the image (default: 10)
exifOrientation : number , // optional, see https://stackoverflow.com/a/32490603/10395024
fileType : string , // optional, fileType override e.g., 'image/jpeg', 'image/png' (default: file.type)
initialQuality : number , // optional, initial quality value between 0 and 1 (default: 1)
alwaysKeepResolution : boolean // optional, only reduce quality, always keep width and height (default: false)
}
imageCompression ( file : File , options : Options ) : Promise < File >
每個瀏覽器都限制瀏覽器 Canvas 物件的最大大小。
因此,我們將圖像大小調整為小於每個瀏覽器限制的最大尺寸。
(但是,影像的proportion/ratio
仍然保留。)
若要使用此功能,請檢查瀏覽器相容性:https://caniuse.com/?search=AbortController
function handleImageUpload ( event ) {
var imageFile = event . target . files [ 0 ] ;
var controller = new AbortController ( ) ;
var options = {
// other options here
signal : controller . signal ,
}
imageCompression ( imageFile , options )
. then ( function ( compressedFile ) {
return uploadToServer ( compressedFile ) ; // write your own logic
} )
. catch ( function ( error ) {
console . log ( error . message ) ; // output: I just want to stop
} ) ;
// simulate abort the compression after 1.5 seconds
setTimeout ( function ( ) {
controller . abort ( new Error ( 'I just want to stop' ) ) ;
} , 1500 ) ;
}
imageCompression . getDataUrlFromFile ( file : File ) : Promise < base64 encoded string >
imageCompression . getFilefromDataUrl ( dataUrl : string , filename : string , lastModified ?: number ) : Promise < File >
imageCompression . loadImage ( url : string ) : Promise < HTMLImageElement >
imageCompression . drawImageInCanvas ( img : HTMLImageElement , fileType ?: string ) : HTMLCanvasElement | OffscreenCanvas
imageCompression . drawFileInCanvas ( file : File , options ?: Options ) : Promise < [ ImageBitmap | HTMLImageElement , HTMLCanvasElement | OffscreenCanvas ] >
imageCompression . canvasToFile ( canvas : HTMLCanvasElement | OffscreenCanvas , fileType : string , fileName : string , fileLastModified : number , quality ?: number ) : Promise < File >
imageCompression . getExifOrientation ( file : File ) : Promise < number > // based on https://stackoverflow.com/a/32490603/10395024
imageCompression . copyExifWithoutOrientation ( copyExifFromFile : File , copyExifToFile : File ) : Promise < File > // based on https://gist.github.com/tonytonyjan/ffb7cd0e82cb293b843ece7e79364233
IE / 邊緣 | 火狐瀏覽器 | 鉻合金 | 狩獵之旅 | iOS 瀏覽器 | 歌劇 |
---|---|---|---|---|---|
IE10、IE11、邊緣 | 最後 2 個版本 | 最後 2 個版本 | 最後 2 個版本 | 最後 2 個版本 | 最後 2 個版本 |
函式庫使用了 Promise API、globalThis 等 ES 功能。如果您需要支援不支援新ES功能的瀏覽器,例如IE。您可以在專案中包含 core-js polyfill。
您可以包含以下腳本來載入 core-js polyfill:
< script src =" https://cdnjs.cloudflare.com/ajax/libs/core-js/3.21.1/minified.min.js " > </ script >
主流瀏覽器都支援 webp 壓縮。請參閱 https://caniuse.com/mdn-api_offscreencanvas_converttoblob_option_type_parameter_webp 以了解瀏覽器相容性。
瀏覽器需要支援「OffscreenCanvas」API 才能利用非阻塞壓縮。如果瀏覽器不支援「OffscreenCanvas」API,則使用主執行緒。請參閱 https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas#browser_compatibility 以了解「OffscreenCanvas」API 的瀏覽器相容性。
Typescript 定義包含在套件中並在package.json
的types
部分中引用
如果您的網站啟用了 CSP 並且您想要使用 Web Worker (useWebWorker: true),請將以下內容新增至回應標頭content-security-policy: script-src 'self' blob: https://cdn.jsdelivr.net
blob:
用於載入Web Worker腳本https://cdn.jsdelivr.net
用於從 Web Worker 腳本內的 CDN 匯入此程式庫。如果您不想從 CDN 載入此庫,您可以在options.libURL
中設定您的自託管庫 URL。 npm run watch
# 它將監視 lib/ 資料夾中的程式碼變更並在 dist/ 資料夾中產生 jsnpm run test