🎁 The Js-Craft Guide to React is now available with a 30% off discount!

Fetch an image and convert it to blob data in React

Let's see how we can use React to fetch an image at a given URL and convert that image to blob data.

To demonstrate this, we will build this small application:
Fetch an image and convert it to blob data in React

Below is the code that will use the fetch() API to retrieve the image, and will return the blob representation of the image.

const DEFAULT_URL = "https://www.js-craft.io/_public-files/cat.png"
const App = () => {
    const [url, setUrl] = React.useState(DEFAULT_URL)

    const fetchAndCovertToBlob = ()=> {
        fetch(url)
            .then( response => response.blob())
            .then( blobData => {
                const {size, type} = blobData
                alert(` 🌅 IMG Type: ${type} \n 🌌 IMG Size: ${size}`)
            });
    }

    return (<div>
        <input type="text" value={url} onChange={e => setUrl(e.target.value)}  />
        <button onClick={fetchAndCovertToBlob}>Fetch img and covert to blob</button>
    </div>)
}

When we will press the button we will get some overall information about that image from the blob data:
Fetch an image and convert it to blob data in React

If you want to actually store and use the blob data you can set it on a state variable:

const [blobData, setBlobData] = React.useState(null)
// ... 
fetch(url)
            .then( response => {
                const data = response.blob()
                setBlobData(data)
                return data
        })
        // continue 

Note that depending on your setup you may need to also take care of the CORS policy or you will get the below error:

Acess to fetch at <<url_here>> from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

For this example, I've set the following code on my images folder server .htaccess file:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

As usual, you can see the full code in its Github repo and play with the live example here.

Also, you can see in this article how to use the generated blob data to facilitate copying and pasting images to the clipboard.

10 Javascript AI projects with Langchain & React

Not sure what to build? Dive in with these Javascript AI projects! Learn how to build LLM powered apps using Langchain.js and React! Connect your apps to LLMs such as OpenAI, create agents, use vector databases, or setup AI context.

10 Javascript AI projects with Langchain & React

Not sure what to build? Dive in with these Javascript AI projects! Learn how to build LLM powered apps using Langchain.js and React! Connect your apps to LLMs such as OpenAI, create agents, use vector databases, or setup AI context.


Leave a Reply

Your email address will not be published. Required fields are marked *

📘 The Guide to React Home Screencasts Best of Newsletter Search X

📘 - 10 Javascript AI projects with React and LangChain

Hi friend! Before you go, just wanted to let you know about the 10 Javascript AI projects ideas with React and LangChain FREE ebook.

One of the best ways to learn is by doing the work. Choose from these 10 project ideas and start working on topics such as:

  • How does LangChain work
  • Connecting to OpenAI LLM
  • Create AI Agents
  • Simple and Sequential Chains
  • Adding Memory (Chat Context)
  • Prompt Templates
  • Using OutputParsers and Tools for Agents
  • Work with Documents and more...

Keep building and see the new capabilities LLM models can add to your React app! Get all projects as an ebook right to your inbox!

X