React Js Convert Image From URL to Base64
React Js Convert Image From URL to Base64 or DataURL:In React.js, converting an image from a URL to Base64 involves fetching the image from a specific URL and encoding its binary data into a Base64 format. First, you use the fetch
API or axios
to retrieve the image from the URL. Then, you convert the response to a Blob object and use FileReader
to read it asynchronously. When the read operation is complete, the image data is available as Base64. This process ensures the image from the URL is transformed into a Base64 representation, allowing it to be easily manipulated and displayed within a React application.




Thanks for your feedback!
Your contributions will help us to improve service.
How can I use Reactjs to convert an image from a URL to a Base64-encoded format?
This React.js code creates a simple web application that converts an image from a given URL to its Base64 representation. It uses React hooks like useState and useEffect. The App component maintains the imageUrl and base64Image states. When the user enters an image URL, it triggers the fetchAndConvertImage function, which fetches the image, converts it to Base64, and updates the state. The converted Base64 image is displayed below the input field. The code also includes some basic HTML elements and CSS classes for styling. Overall, it's a concise example of how to perform image conversion in a React application
React Js Convert Image From URL To Base64 Example
xxxxxxxxxx
<script type="text/babel">
const { useState, useEffect } = React;
function App() {
const [imageUrl, setImageUrl] = useState(
'https://www.sarkarinaukriexams.com/images/bio/1695897671-bio.png'
);
const [base64Image, setBase64Image] = useState('');
useEffect(() => {
if (imageUrl) {
fetchAndConvertImage();
}
}, [imageUrl]);
const fetchAndConvertImage = async () => {
try {
const base64data = await fetchAndConvert(imageUrl);
setBase64Image(base64data);
} catch (error) {
console.error('Error fetching and converting image:', error);
}
};
const fetchAndConvert = async (url) => {
const data = await fetch(url);
const blob = await data.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
const base64data = reader.result;
resolve(base64data);
};
});
};
return (
<div className='container'>
<h3>React Js Convert Image from URl to Base64 </h3>
<input
type="text"
className='input-field' // added className to the input element
placeholder="Enter image URL"
value={imageUrl}
onChange={(e) => setImageUrl(e.target.value)}
/>
<br />
<p className='base64-text'>Base64 : {base64Image}</p> {/* added className to the paragraph element */}
{base64Image && <img className='converted-image' src={base64Image} alt="Converted" />} {/* added className to the image element */}
</div>
);
}
ReactDOM.render(<App />, document.getElementById('app'));
</script>