Display Images in an Image Viewer - React JS

This tutorial shows how to load, display, and save images using the LEADTOOLS SDK in React.JS.

Overview  
Summary This tutorial covers how to load, display, and save image in a React JS application.
Completion Time 15 minutes
Visual Studio Project Download tutorial project (553 KB)
Platform React JS Web Application
IDE Visual Studio Code - Client
Development License Download LEADTOOLS
Try it in another language

Required Knowledge

Get familiar with the basic steps of creating a project by reviewing the Add References and Set a License tutorial, before working on the Display Images in an Image Viewer - React JS tutorial.

Create the Project and Add LEADTOOLS References

To create the project structure open the command line console and cd into the location where the project is to be created. Then run the following command:

npx create-react-app <APP NAME> --template typescript

The references needed depend upon the purpose of the project. For this project, the following JS files are needed and located at <INSTALL_DIR>\LEADTOOLS23\Bin\JS:

Make sure to copy both files to the public\Common folder and import them in the public\index.html file.

Set the License File

The License unlocks the features needed for the project. It must be set before any toolkit function is called. For details, including tutorials for different platforms, refer to Setting a Runtime License.

There are two types of runtime licenses:

Note Adding LEADTOOLS local references and setting a license are covered in more detail in the Add References and Set a License tutorial.

Initialize the Image Viewer

With the project created, the references added, and the license set, coding can begin.

Create a new folder within the src folder and name it Components, inside of this folder create a new file and name it ImageViewer.tsx. Add the following code to ImageViewer.tsx:

///<reference path="../../public/Common/Leadtools.Controls.d.ts" /> 
import { ChangeEvent, useEffect, useRef, useState } from "react"; 
 
function ImageViewer() { 
  const imageViewerRef = useRef(null); 
  const [chosenFile, setChosenFile] = useState( 
    "https://demo.leadtools.com/images/jpeg/cannon.jpg" 
  ); 
  const [imageViewer, setImageViewer] = useState<lt.Controls.ImageViewer>(); 
 
  // On component mount, create the ImageViewer 
  useEffect(() => { 
    createImageViewer(); 
  }, []); 
 
  function createImageViewer() { 
    if (imageViewerRef.current) { 
      const createOptions = new lt.Controls.ImageViewerCreateOptions( 
        imageViewerRef.current 
      ); 
      const imageViewer = new lt.Controls.ImageViewer(createOptions); 
      imageViewer.viewVerticalAlignment = lt.Controls.ControlAlignment.center; 
      imageViewer.viewHorizontalAlignment = lt.Controls.ControlAlignment.center; 
      imageViewer.autoCreateCanvas = true; 
      imageViewer.imageUrl = chosenFile; 
      setImageViewer(imageViewer); 
    } 
  } 
 
  // When file is uploaded, make sure it is valid then update the state 
  const handleFileUpload = (e: ChangeEvent<HTMLInputElement>) => { 
    const selectedFile = e.target.files && e.target.files[0]; 
    if (selectedFile) { 
      const newChosenFile = URL.createObjectURL(selectedFile); 
      setChosenFile(newChosenFile); 
    } 
  }; 
 
  // When the state is updated, update the imageUrl 
  useEffect(() => { 
    if (imageViewer) imageViewer.imageUrl = chosenFile; 
  }, [chosenFile]); 
 
  // Download the Image 
  const handleDownloadClick = async () => { 
    if (chosenFile) { 
      try { 
        const response = await fetch(chosenFile); 
        const blob = await response.blob(); 
        const url = URL.createObjectURL(blob); 
        const link = document.createElement('a'); 
        link.href = url; 
        link.download = 'downloaded-image.jpg'; 
        link.click(); 
        URL.revokeObjectURL(url); 
      } catch (error) { 
        console.error('Error downloading image:', error); 
      } 
    } 
  }; 
 
  return ( 
    <> 
      <input className="file-input" type="file" onChange={handleFileUpload} accept=".jpg,.jpeg,.png" /> 
      <div 
        ref={imageViewerRef} 
        style={{ height: "720px", width: "1280px" }} 
      ></div> 
      <button onClick={handleDownloadClick}>Save Image</button> 
    </> 
  ); 
} 
 
export default ImageViewer; 

Add the Load Image and Save Image Code

Open src\App.js file and modify the HTML with the below code:

import React from 'react'; 
import logo from './logo.svg'; 
import './App.css'; 
 
function App() { 
   
  return ( 
    <div className="App"> 
      <header className="App-header"> 
        			<div class="tutorial-image"><img src={logo} className="App-logo" alt="logo" /></div> 
        <p> 
          Loading and Saving an Image example 
        </p> 
 
        <p>Image Viewer Below</p> 
         
        <input type="file" id="file-input" accept=".jpg,.jpeg,.png"></input> 
        <button id="addToViewer">Add Image To Viewer</button> 
        <a id="download" download="new-image-name.jpg"> save image </a> 
         
        <div id="imageViewerDiv"></div>        
         
      </header> 
    </div> 
  ); 
} 
 
export default App; 

Inside of the App.tsx file change the App functions return statement to:

return ( 
    <div className="App"> 
      <header className="App-header"> 
        <p>Displaying an Image Example</p> 
        <ImageViewer /> 
      </header> 
    </div> 
  ); 

Add the following CSS class to App.css

.file-input { 
  padding: 20px; 
} 

Run the project

Open the command line console, then cd into the root of the React project. From there, run npm start.

This will build the React application, and the ImageViewer will now be loaded into the browser.

ImageViewer displayed

To load a new RasterImage into the ImageViewer, click Choose File and choose an image. Then press Add Image to Viewer to display the image. To export the image click the Save Image button and the image will begin to download.

Wrap-up

This tutorial showed how to load, display, and save images. In addition, it showed how to use the ImageViewer object.

See Also

Help Version 23.0.2024.5.22
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2024 LEAD Technologies, Inc. All Rights Reserved.

Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.