在网络浏览器中运行的 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