ArticleZip > Download An Image Using Axios And Convert It To Base64

Download An Image Using Axios And Convert It To Base64

Are you looking to download an image using Axios and then convert it to Base64 in your coding project? Well, you're in the right place! In this article, we'll guide you through the steps to achieve this with ease.

First things first, you need to make sure you have Axios installed in your project. If you haven't already done this, you can easily add Axios to your project using npm by running the following command:

Bash

npm install axios

Once you have Axios in your project, you can start writing the code to download an image and convert it to Base64. The following code snippet demonstrates how you can achieve this:

Javascript

const axios = require('axios');
const fs = require('fs');

const downloadImage = async (url, outputPath) => {
  const response = await axios({
    url: url,
    method: 'GET',
    responseType: 'arraybuffer',
  });

  fs.writeFileSync(outputPath, response.data, 'binary');
};

const convertImageToBase64 = (imagePath) => {
  const image = fs.readFileSync(imagePath);
  const base64Image = Buffer.from(image).toString('base64');
  return base64Image;
};

const imageUrl = 'https://example.com/image.jpg';
const outputPath = 'downloaded_image.jpg';

downloadImage(imageUrl, outputPath)
  .then(() => {
    const base64Image = convertImageToBase64(outputPath);
    console.log(base64Image);
  })
  .catch((error) => {
    console.error('An error occurred:', error);
  });

In the code snippet above, we first define a function `downloadImage` that uses Axios to make a GET request to download the image from the specified URL. The image data is then saved to a file on your local system.

Next, we define a function `convertImageToBase64` that reads the downloaded image file and converts it to Base64 format using Node.js `Buffer`.

To use these functions, simply provide the URL of the image you want to download and the path where you want to save the downloaded image. After downloading the image, the code will automatically convert it to Base64 and log the Base64 representation to the console.

By following these simple steps, you can easily download an image using Axios and convert it to Base64 in your coding project. This approach can be handy when you need to work with images in your applications or when you need to transmit image data in a Base64-encoded format.

Remember to handle any errors that may arise during the download or conversion process to ensure the robustness of your code. Happy coding!

×