![Oracle Drags Its Feet in the JavaScript Trademark Dispute](https://cdn.sanity.io/images/cgdhsj6q/production/919c3b22c24f93884c548d60cbb338e819ff2435-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
browser-image-compression
Advanced tools
The browser-image-compression npm package is a JavaScript library that allows you to compress images directly in the browser. It is useful for reducing the file size of images before uploading them to a server, which can save bandwidth and improve performance.
Compress Image
This feature allows you to compress an image file to a specified size and dimension. The code sample demonstrates how to use the package to compress an image file with a maximum size of 1MB and a maximum width or height of 1920 pixels.
const imageCompression = require('browser-image-compression');
async function compressImage(file) {
const options = {
maxSizeMB: 1,
maxWidthOrHeight: 1920,
useWebWorker: true
};
try {
const compressedFile = await imageCompression(file, options);
console.log('Compressed file:', compressedFile);
} catch (error) {
console.error('Error compressing image:', error);
}
}
Get Image File from URL
This feature allows you to fetch an image from a URL and convert it into a File object. The code sample demonstrates how to fetch an image from a URL and create a File object from the fetched Blob.
const imageCompression = require('browser-image-compression');
async function getImageFileFromUrl(url) {
try {
const response = await fetch(url);
const blob = await response.blob();
const file = new File([blob], 'image.jpg', { type: blob.type });
console.log('Image file:', file);
} catch (error) {
console.error('Error fetching image:', error);
}
}
Draw Image on Canvas
This feature allows you to draw an image on a canvas element. The code sample demonstrates how to read an image file, create an Image object, and draw it on a canvas element.
const imageCompression = require('browser-image-compression');
function drawImageOnCanvas(file) {
const img = new Image();
const reader = new FileReader();
reader.onload = function (e) {
img.src = e.target.result;
img.onload = function () {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
document.body.appendChild(canvas);
};
};
reader.readAsDataURL(file);
}
Compressor.js is a JavaScript library for image compression. It provides a simple API for compressing images in the browser. Compared to browser-image-compression, Compressor.js offers more customization options for the compression process, such as setting the quality and resizing the image.
Pica is a high-quality image resizing library that works in the browser. It focuses on providing high-quality image resizing with a fast performance. While it does not specifically focus on compression, it can be used to resize images before compressing them with another library like browser-image-compression.
Image-shrink is a lightweight JavaScript library for compressing images in the browser. It provides a simple API for reducing the file size of images. Compared to browser-image-compression, image-shrink is more lightweight but may not offer as many features or customization options.
Javascript module to be run in the web browser for image compression.
You can download imageCompression from the dist folder. Alternatively, you can install it via yarn or npm
npm install browser-image-compression --save
or
yarn add browser-image-compression
or use a CDN like delivrjs:
https://cdn.jsdelivr.net/npm/browser-image-compression@1.0.12/dist/browser-image-compression.js
or
https://cdn.jsdelivr.net/npm/browser-image-compression@latest/dist/browser-image-compression.js
(can be used in framework like React, Angular, Vue etc)
(work with bundler like webpack and rollup)
import imageCompression from 'browser-image-compression';
or
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/browser-image-compression@latest/dist/browser-image-compression.js"></script>
// you should provide one of maxSizeMB, maxWidthOrHeight in the options
const 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)
useWebWorker: boolean, // optional, use multi-thread web worker, fallback to run in main-thread (default: true)
maxIteration: number, // optional, max number of iteration to compress the image (default: 10)
exifOrientation: number, // optional, see https://stackoverflow.com/a/32490603/10395024
onProgress: Function, // optional, a function takes one progress argument (percentage from 0 to 100)
fileType: string // optional, fileType override
}
imageCompression(file: File, options): Promise<File | Blob>
imageCompression.getDataUrlFromFile(file: File | Blob): Promise<base64 encoded string>
imageCompression.getFilefromDataUrl(dataUrl: string, filename: string, lastModified?: number): Promise<File>
imageCompression.loadImage(url: string): Promise<HTMLImageElement>
imageCompression.drawImageInCanvas(img: HTMLImageElement): HTMLCanvasElement | OffscreenCanvas
imageCompression.drawFileInCanvas(file: File| Blob): Promise<[ImageBitmap | HTMLImageElement, HTMLCanvasElement | OffscreenCanvas]>
imageCompression.canvasToFile(canvas: HTMLCanvasElement | OffscreenCanvas, fileType: string, fileName: string, fileLastModified: number, quality?: number): Promise<File | Blob>
imageCompression.getExifOrientation(file: File| Blob): Promise<number> // based on https://stackoverflow.com/a/32490603/10395024
<input type="file" accept="image/*" onchange="handleImageUpload(event);">
async await syntax:
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);
}
}
Promise.then().catch() syntax:
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);
});
}
open https://donaldcwl.github.io/browser-image-compression/example/basic.html
or check the "example" folder in this repo
![]() IE / Edge | ![]() Firefox | ![]() Chrome | ![]() Safari | ![]() Opera | ![]() Chrome for Android |
---|---|---|---|---|---|
IE10, IE11, Edge | last 2 versions | last 2 versions | last 2 versions | last 2 versions | last 2 versions |
Promise API is being used in this library. If you need to support browser that do not support Promise like IE. You can include the Promise polyfill in your project.
See: https://github.com/taylorhakes/promise-polyfill
You can include the following script to load the Promise polyfill:
<script src="https://cdn.jsdelivr.net/npm/promise-polyfill@8/dist/polyfill.min.js"></script>
npm install --save-dev @types/browser-image-compression
or
yarn add --dev @types/browser-image-compression
npm run watch
# it will watch code change in lib/ folder and generate js in dist/ foldernpm run test
v1.0.12 (4 Jun 2020)
FAQs
Compress images in the browser
The npm package browser-image-compression receives a total of 0 weekly downloads. As such, browser-image-compression popularity was classified as not popular.
We found that browser-image-compression demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.