avatarJohn Au-Yeung

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3322

Abstract

Name</span>=<span class="hljs-string">"App"</span>></span> <span class="hljs-tag"><<span class="hljs-name">input</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{onChange}</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"file"</span> /></span> <span class="hljs-tag"></<span class="hljs-name">div</span>></span></span> ); }</pre></div><p id="47f1">We have the <code>resizeFile</code> function that takes the image file and returns the promise to resize and compress the file.</p><p id="ed2e">The first argument is the file object.</p><p id="0433">The 2nd and 3rd are the width and height.</p><p id="a5a0">The 4th is the format to convert to.</p><p id="5099">The 5th is the quality of the image from 0 to 100.</p><p id="b817">The 6th is the rotation of the image.</p><p id="5ad9">The 7th is a function for getting the new image URI.</p><p id="5ee5">The 8th is the format.</p><p id="9a00">It takes 2 more arguments for the min-width and height.</p><p id="5d93">In the <code>onChange</code> handler, we get the file from the file input.</p><p id="b892">Once we did that we can do the upload.</p><h1 id="29ee">Upload the File</h1><p id="f2d2">To upload the file, we write:</p><div id="7f5c"><pre><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>; <span class="hljs-keyword">import</span> Resizer <span class="hljs-keyword">from</span> <span class="hljs-string">"react-image-file-resizer"</span>;</pre></div><div id="50fb"><pre>const resizeFile = <span class="hljs-function"><span class="hljs-params">(file)</span> =></span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">(resolve)</span> =></span> { Resizer.imageFileResizer( file, <span class="hljs-number">300</span>, <span class="hljs-number">400</span>, <span class="hljs-string">"JPEG"</span>, <span class="hljs-number">80</span>, <span class="hljs-number">0</span>, <span class="hljs-function"><span class="hljs-params">(uri)</span> =></span> { resolve(uri); }, <span class="hljs-string">"base64"</span> ); });</pre></div><div id="cde1"><pre><span class="hljs-keyword">const</span> dataURIToBlob = (dataURI) => { <span class="hljs-keyword">const</span> splitDataURI = dataURI.<span class="hljs-keyword">split</span>(<span class="hljs-string">","</span>); <span class="hljs-keyword">const</span> byteString = splitDataURI[0].indexOf(<span class="hljs-string">"base64"</span>) >= 0 ? atob(splitDataURI[1]) : decodeURI(splitDataURI[1]); <span class="hljs-keyword">const</span> mimeString = splitDataURI[0].<span class="hljs-keyword">split</span>(<span class="hljs-string">":"</span>)[1].<span class="hljs-keyword">split</span>(<span class="hljs-string">";"</span>)[0];</pre></div><div id="2c6a"><pre> const ia <span class="hljs-operator">=</span> new Uint8Array(byteString.length)<span class="hljs-comment">;</span> for (let i <span class="hljs-operator">=</span> <span class="hljs-number">0</span><span class="hljs-comment">; i < byteString.length; i++) ia[i] = byteString.charCodeAt(i);</span></pre></div><div id="7f

Options

b5"><pre> <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Blob([ia], { <span class="hljs-keyword">type</span>: mimeString }); };</pre></div><div id="7a44"><pre><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">App</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">const</span> <span class="hljs-title function_">onChange</span> = <span class="hljs-keyword">async</span> (<span class="hljs-params">event</span>) => { <span class="hljs-keyword">const</span> file = event.<span class="hljs-property">target</span>.<span class="hljs-property">files</span>[<span class="hljs-number">0</span>]; <span class="hljs-keyword">const</span> image = <span class="hljs-keyword">await</span> <span class="hljs-title function_">resizeFile</span>(file); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(image); <span class="hljs-keyword">const</span> newFile = <span class="hljs-title function_">dataURIToBlob</span>(image); <span class="hljs-keyword">const</span> formData = <span class="hljs-keyword">new</span> <span class="hljs-title class_">FormData</span>(); formData.<span class="hljs-title function_">append</span>(<span class="hljs-string">"image"</span>, newFile); <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetch</span>( <span class="hljs-string">"https://run.mocky.io/v3/c5189845-2a93-49aa-85c7-70bc64e8af90"</span>, { <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>, <span class="hljs-attr">body</span>: formData } ); <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.<span class="hljs-title function_">text</span>(); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data); };</pre></div><div id="4985"><pre> <span class="hljs-keyword">return</span> ( <span class="language-xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>></span> <span class="hljs-tag"><<span class="hljs-name">input</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{onChange}</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"file"</span> /></span> <span class="hljs-tag"></<span class="hljs-name">div</span>></span></span> ); }</pre></div><p id="40e3">We added the <code>dataURItoBlob</code> function to convert the base64 string back to a file.</p><p id="7800">It looks through the byte string created from the base64 string and put it in a Uint8Array.</p><p id="1acc">Then that’s put in the <code>Blob</code> constructor to return the file object.</p><p id="c40d">Once we did that, we put that in the <code>FormData</code> constructor.</p><p id="a500">Then we upload it with the <code>fetch</code> function.</p><h1 id="080d">Conclusion</h1><p id="a7c3">We can compress and resize images before uploading it in a React app with the React Image File Resizer package.</p></article></body>

Compress Images Before Upload in React with React Image File Resizer

Photo by Viktor Talashuk on Unsplash

The React Image File Resizer lets us compress and manipulate our images before we upload them.

In this article, we’ll look at how to manipulate our image before uploading in a React app.

Installation

We can install the package by running:

npm i react-image-file-resizer

or

yarn add react-image-file-resizer

Compressing and Manipulating Images

We can compress and manipulate our image that we select from a file input.

To do that, we write:

import React from "react";
import Resizer from "react-image-file-resizer";
const resizeFile = (file) =>
  new Promise((resolve) => {
    Resizer.imageFileResizer(
      file,
      300,
      400,
      "JPEG",
      80,
      0,
      (uri) => {
        resolve(uri);
      },
      "base64"
    );
  });
export default function App() {
  const onChange = async (event) => {
    const file = event.target.files[0];
    const image = await resizeFile(file);
    console.log(image);
  };
  return (
    <div className="App">
      <input onChange={onChange} type="file" />
    </div>
  );
}

We have the resizeFile function that takes the image file and returns the promise to resize and compress the file.

The first argument is the file object.

The 2nd and 3rd are the width and height.

The 4th is the format to convert to.

The 5th is the quality of the image from 0 to 100.

The 6th is the rotation of the image.

The 7th is a function for getting the new image URI.

The 8th is the format.

It takes 2 more arguments for the min-width and height.

In the onChange handler, we get the file from the file input.

Once we did that we can do the upload.

Upload the File

To upload the file, we write:

import React from "react";
import Resizer from "react-image-file-resizer";
const resizeFile = (file) =>
  new Promise((resolve) => {
    Resizer.imageFileResizer(
      file,
      300,
      400,
      "JPEG",
      80,
      0,
      (uri) => {
        resolve(uri);
      },
      "base64"
    );
  });
const dataURIToBlob = (dataURI) => {
  const splitDataURI = dataURI.split(",");
  const byteString =
    splitDataURI[0].indexOf("base64") >= 0
      ? atob(splitDataURI[1])
      : decodeURI(splitDataURI[1]);
  const mimeString = splitDataURI[0].split(":")[1].split(";")[0];
  const ia = new Uint8Array(byteString.length);
  for (let i = 0; i < byteString.length; i++) ia[i] = byteString.charCodeAt(i);
  return new Blob([ia], { type: mimeString });
};
export default function App() {
  const onChange = async (event) => {
    const file = event.target.files[0];
    const image = await resizeFile(file);
    console.log(image);
    const newFile = dataURIToBlob(image);
    const formData = new FormData();
    formData.append("image", newFile);
    const res = await fetch(
      "https://run.mocky.io/v3/c5189845-2a93-49aa-85c7-70bc64e8af90",
      {
        method: "POST",
        body: formData
      }
    );
    const data = await res.text();
    console.log(data);
  };
  return (
    <div className="App">
      <input onChange={onChange} type="file" />
    </div>
  );
}

We added the dataURItoBlob function to convert the base64 string back to a file.

It looks through the byte string created from the base64 string and put it in a Uint8Array.

Then that’s put in the Blob constructor to return the file object.

Once we did that, we put that in the FormData constructor.

Then we upload it with the fetch function.

Conclusion

We can compress and resize images before uploading it in a React app with the React Image File Resizer package.

Programming
Web Development
Software Development
JavaScript
React
Recommended from ReadMedium