Categories
JavaScript Answers

How to load an image from URL into buffer in Node.js and JavaScript?

Spread the love

Sometimes, we want to load an image from URL into buffer in Node.js and JavaScript.

In this article, we’ll look at how to load an image from URL into buffer in Node.js and JavaScript.

How to load an image from URL into buffer in Node.js and JavaScript?

To load an image from URL into buffer in Node.js and JavaScript, we use Axios.

For instance, we write

const response = await axios.get(url, { responseType: "arraybuffer" });
const buffer = Buffer.from(response.data, "utf-8");

to make a get request to the image url with axios.get.

We get the response as an array buffer by setting the responseType to 'arraybuffer'.

And then we call Buffer.from to convert the response.data response we get from the promise returned by get body to a buffer.

Conclusion

To load an image from URL into buffer in Node.js and JavaScript, we use Axios.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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