Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to compress an image Javascript React Web App

I'm looking for the best solution to compress images that's I receive and need to store in my database.

Actually, I convert an image in base64 and then send it to the server.

handleImage = e => {
    e.preventDefault();
    let reader = new FileReader();
    let file = e.target.files[0];

    reader.onloadend = () => {           
        this.setState({
            file: file,
            image: reader.result
        });
    }

    this.setState({ imgchange: true })
}

And then send the current image in state to the server. But with the low quality image it's fine but when I try to upload a medium-high quality I can't save it on the server, I need a method to compress the image.

Have you any idea to achieve this? Can you show me an example?

like image 507
CoffeAbuser Avatar asked Dec 23 '17 21:12

CoffeAbuser


People also ask

How do I compress images in React JS?

We can resize, compress and convert the images based on our requirements. To compress your images follow these three simple steps: Install the package using npm/yarn. Add the particular code block to your project.

How do I compress an image in HTML?

One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels.


2 Answers

Best npm package you can use for image compression is browser-image-compression. Tested in React and Redux.

  • Install npm install browser-image-compression --save

async await syntax:

import React from "react";
import imageCompression from 'browser-image-compression';
function photoUpload() {
    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);
        }

      }
  return (
    <>
     <div>
     <input type="file" accept="image/*" onChange={event => handleImageUpload(event)}/>
     </div>
    </>
  );
}

export default photoUpload;

For more in details can check on NPM

like image 184
Maheshvirus Avatar answered Sep 17 '22 13:09

Maheshvirus


you can use react-image-file-resizer library to compress image

import Resizer from 'react-image-file-resizer';


Resizer.imageFileResizer(
    file, //is the file of the new image that can now be uploaded...
    maxWidth, // is the maxWidth of the  new image
    maxHeight, // is the maxHeight of the  new image
    compressFormat, // is the compressFormat of the  new image
    quality, // is the quality of the  new image
    rotation, // is the rotatoion of the  new image
    responseUriFunc,  // is the callBack function of the new image URI
    outputType  // is the output type of the new image
    );

For Example:

import React, { Component } from 'react';
import Resizer from 'react-image-file-resizer';

class App extends Component {
    constructor(props) {
        super(props);
        this.fileChangedHandler = this.fileChangedHandler.bind(this);
    }

    fileChangedHandler(event) {
        var fileInput = false
        if(event.target.files[0]) {
            fileInput = true
        }
        if(fileInput) {
            Resizer.imageFileResizer(
                event.target.files[0],
                300,
                300,
                'JPEG',
                100,
                0,
                uri => {
                    console.log(uri)
                },
                'base64'
            );
        }
    }

    render() {
        return (
            <div className="App">
                <input type="file" onChange={this.fileChangedHandler}/>
            </div>
        );
    }
}

export default App;

For Details you can read this documentation

like image 29
Jagdish Bhatt Avatar answered Sep 18 '22 13:09

Jagdish Bhatt