Modul Javascript untuk dijalankan di browser web untuk kompresi gambar.
buka https://donaldcwl.github.io/browser-image-compression/example/basic.html
atau periksa folder "contoh" di repo ini
< 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 ) ;
} ) ;
}
Anda dapat menginstalnya melalui npm atau benang
npm install browser-image-compression --save
# or
yarn add browser-image-compression
import imageCompression from 'browser-image-compression' ;
(dapat digunakan dalam kerangka kerja seperti React, Angular, Vue dll)
(bekerja dengan bundler seperti webpack dan rollup)
Anda dapat mengunduh imageCompression dari folder dist.
Alternatifnya, Anda dapat menggunakan CDN seperti delivrjs:
< script type =" text/javascript " src =" https://cdn.jsdelivr.net/npm/[email protected]/dist/browser-image-compression.js " > </ script >
Jika proyek ini membantu Anda mengurangi waktu pengembangan, Anda dapat membelikan saya secangkir kopi :)
(didukung oleh Stripe)
// 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 >
Setiap browser membatasi ukuran maksimum objek Canvas browser.
Jadi, kami mengubah ukuran gambar menjadi kurang dari ukuran maksimum yang dibatasi oleh setiap browser.
(Namun, proportion/ratio
gambar tetap ada.)
Untuk menggunakan fitur ini, silakan periksa kompatibilitas browser: 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
YAITU / Tepi | Firefox | krom | Safari | Safari iOS | Opera |
---|---|---|---|---|---|
IE10, IE11, Tepi | 2 versi terakhir | 2 versi terakhir | 2 versi terakhir | 2 versi terakhir | 2 versi terakhir |
Library ini menggunakan fitur ES seperti Promise API, globalThis. Jika Anda perlu mendukung browser yang tidak mendukung fitur ES baru seperti IE. Anda dapat menyertakan polyfill core-js dalam proyek Anda.
Anda dapat menyertakan skrip berikut untuk memuat polyfill core-js:
< script src =" https://cdnjs.cloudflare.com/ajax/libs/core-js/3.21.1/minified.min.js " > </ script >
Kompresi webp didukung di browser utama. Silakan lihat https://caniuse.com/mdn-api_offscreencanvas_converttoblob_option_type_parameter_webp untuk kompatibilitas browser.
Browser perlu mendukung API "OffscreenCanvas" untuk memanfaatkan kompresi non-pemblokiran. Jika browser tidak mendukung API "OffscreenCanvas", thread utama akan digunakan. Lihat https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas#browser_compatibility untuk kompatibilitas browser API "OffscreenCanvas".
Definisi skrip ketikan disertakan dalam paket & direferensikan di bagian types
pada package.json
Jika situs web Anda mengaktifkan CSP dan Anda ingin menggunakan Web Worker (useWebWorker: true), harap tambahkan yang berikut ini ke header respons content-security-policy: script-src 'self' blob: https://cdn.jsdelivr.net
blob:
untuk memuat skrip Pekerja Webhttps://cdn.jsdelivr.net
untuk mengimpor perpustakaan ini dari CDN ke dalam skrip Web Worker. Jika Anda tidak ingin memuat perpustakaan ini dari CDN, Anda dapat mengatur URL perpustakaan yang dihosting sendiri di options.libURL
. npm run watch
# itu akan melihat perubahan kode di folder lib/ dan menghasilkan js di folder dist/npm run test