Giter Site home page Giter Site logo

alextanhongpin / compress.js Goto Github PK

View Code? Open in Web Editor NEW
134.0 4.0 29.0 9.16 MB

A simple JavaScript based client-side image compression algorithm

License: MIT License

JavaScript 100.00%
compress base-conversion compression javascript javascript-client canvas fastest base64url base64 image

compress.js's Introduction

compress.js

A JavaScript client side image compression. This library uses the Canvas API to compress the image, and thus will not work on the node.js server-side.

Advantage:

  • quick compression on the client-side
  • compress multiple images and convert them to base64 string
  • save data by compressing it on the client-side before sending to the server
  • automatically resize the image to max 1920px (width or height, but mantains the aspect ratio of the images)
  • fix image rotation issue when uploading images from Android an iOS

NOTE:

There are several limitations for this library:

  • When working with image/gif, the compressed image will no longer animate.
  • When working with image/png with transparent background, the compressed image will lose transparency and result in black background.

Installation

NPM Package here.

npm install compress.js --save

Import

const Compress = require('compress.js')

Demo

Try out our demo here.

Usage

// Initialization
const compress = new Compress()

// Attach listener
const upload = document.getElementById('upload')
upload.addEventListener('change', function (evt) {
  const files = [...evt.target.files]
  compress.compress(files, {
    size: 4, // the max size in MB, defaults to 2MB
    quality: .75, // the quality of the image, max is 1,
    maxWidth: 1920, // the max width of the output image, defaults to 1920px
    maxHeight: 1920, // the max height of the output image, defaults to 1920px
    resize: true, // defaults to true, set false if you do not want to resize the image width and height
    rotate: false, // See the rotation section below
  }).then((data) => {
    // returns an array of compressed images
  })
}, false)


// or simpler
compress.attach('#upload', {
  size: 4,
  quality: .75
}).then((data) => {
  // do something with the compressed image
})
// example output
[{
  alt: '10mb-image.jpg',
  data: '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD...',
  elapsedTimeInSeconds: 1.9292250000000004,
  endHeightInPx: 1280,
  endSizeInMb: 0.44418832116788315,
  endWidthInPx: 1920,
  ext: 'image/jpeg',
  initialHeightInPx: 3744,
  initialSizeInMb: 8.989774,
  initialWidthInPx: 5616,
  iterations: 1,
  prefix: 'data:jpeg;base64,'
  quality: 0.75,
  sizeReducedInPercent: 95.058960089899,
}]

You can even convert the compressed base64 string to a file before uploading to the server:

compress.attach('#upload', {
  size: 4,
  quality: .75
}).then((results) => {
  // Example mimes:
  // image/png, image/jpeg, image/jpg, image/gif, image/bmp, image/tiff, image/x-icon,  image/svg+xml, image/webp, image/xxx, image/png, image/jpeg, image/webp
  // If mime is not provided, it will default to image/jpeg
  const img1 = results[0]
  const base64str = img1.data
  const imgExt = img1.ext
  const file = Compress.convertBase64ToFile(base64str, imgExt)
  // -> Blob {size: 457012, type: "image/png"}
})

Rotation

To enable auto-rotation based on browsers support for exif-orientation, pass the rotate options in the config.

// Use Modernizr to detect if exit-orientation is supported.
const browserSupportsExifOrientation = () => {
  return new Promise((resolve) => Modernizr.on("exiforientation", resolve));
};

// Only rotate if browser does not support exit orientation.
const shouldRotate = async () => {
  const supported = await browserSupportsExifOrientation();
  return !supported;
};

const rotate = await shouldRotate();

// When compressing ...
compress.compress(files, {
    ...
    rotate, // Pass the rotation here
  })

compress.js's People

Contributors

alextanhongpin avatar corporateuser avatar craigcav avatar ucare-wuh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

compress.js's Issues

Cropp error

When I get another image and try to crop it without updating the page, a cropping error happens.
Cropp for the first time:
https://ibb.co/w40qzQK

Cropp for the second time without updating the page:
https://ibb.co/x8htNy4

It happens with the same or another image.

Facing issue in importing nextjs

When I try to use compress.js latest version i.e. 1.2.1 then it shows a build error that regenerator runtime cannot import from outside the module. Please look into it.

Exif orientation support broken with Safari 13.1 (iOS and Desktop)

In Safari 13.1 (released a few days ago on iOS as part of iOS 13.4.1), the EXIF orientation value is no longer being handled properly, and the compressed image that is output will not have the correct orientation.

I believe that this change in Webkit (used by Safari) is the source of the problem: https://bugs.webkit.org/show_bug.cgi?id=201123

The required action for this library would be to ignore the EXIF orientation value when on Safari 13.1 (or later).

The easiest way to reproduce this is to go to the https://davidmoodie.com/client-compress/ demo site using a Safari or Chome browser on a device running iOS 13.4.1 and attempt to upload the attached image. This image has orientation EXIF value of 3 (rotated 180 degrees).

The demo page will return the image rendered upside down. However, the same image on a device not running iOS 13.4.1 will return the image rendered with the proper orientation.

Demo-browser-on-iPhone-running-ios-13 4 1
IMG_2119

How to use this?

I just trying for a couple days but, why I can't upload compressed image or change image value in the html image input?

Transparency lost on png images

Hi,

Thanks for this awesome library, it's very handy and simple.
However, if I try to compress a png image with transparency,
the transparent parts would turn into black as result.

Is there anyway to solve this?

Thanks for all the good works again!

P.S. This is what looks like on the demo page, the original image is here.
08_x_08_17-05-43

Why you use jpeg ?

Hi @alextanhongpin,

I want to know why you use exclusively the jpeg format to output the image ?
Why not png ?

It is possible to add param to custom that ?

Thanks.

Error when running jest

I'm getting an error when running jest

/node_modules/compress.js/src/index.js:2
    import "regenerator-runtime/runtime.js";
    ^^^^^^
SyntaxError: Cannot use import statement outside a module

import Compress from 'compress.js'

No idea what to do here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.