šŸ“• LangChain for JavaScript developers is now out!
Build 5 Next.js apps with ChatGPT integrated features using LangChain.

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.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

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