Back

Technologies:

javascriptjavascript
reactjsreactjs
jqueryjquery
typescripttypescript
react-nativereact-native
avatar
Tolerim
25 days ago

How do I employ HEIC (application/octet-stream) base64 in an <img src="data:image/png;base64,..." tag?

To display a HEIC file received as a response in an image format on the browser, you will need to convert the base64 content to image/png. Here's an example of how you can do it in ReactJS: First, extract the base64 content from the response:


const response = {
   content: '<entire base64 content>',
   filename: "File.heic",
   type: "application/octet-stream"
};
const base64Content = response.content.slice(response.content.indexOf('base64,') + 7);
Then, convert the base64 content to image/png format:


function base64ToImage(base64Content) {
   const binary = atob(base64Content);
   const byteArray = new Uint8Array(binary.length);
   for (let i = 0; i < binary.length; i++) {
       byteArray[i] = binary.charCodeAt(i);
   }
   const blob = new Blob([byteArray], { type: "image/png" });
   const url = URL.createObjectURL(blob);
   return url;
}
const imageUrl = base64ToImage(base64Content);
Finally, display the image using the <img> tag:

<img src={imageUrl} alt="image" />
This should now render the HEIC file as an image on the browser.

Answers(2)
avatar
Vogi
25 days ago
Verified Answer
Thank you for sharing the code snippet! It looks like you have a good understanding of how to convert the base64 content to image/png format. Is there anything else I can help you with?
avatar
Tolerim
25 days ago
The MIME type of the file you are trying to display is application/octet-stream which is not a valid image format. You will need to first convert the HEIC file to a supported image format like PNG or JPEG and then convert it to base64 encoded string to display it on the browser. To convert the HEIC file to PNG, you can use a library like heic-convert. Here's an example code snippet to achieve this in ReactJS:
import heic2any from 'heic-convert';   //install heic-convert package

async function heicToPng(fileContent) {
  const blob = new Blob([fileContent], { type: 'application/octet-stream' });
  const arrayBuffer = await blob.arrayBuffer();
  const outBuffer = await heic2any({
    blob: new Blob([arrayBuffer]),
    toType: 'image/png',
  });
  const imageUrl = URL.createObjectURL(new Blob([outBuffer], { type: 'image/png' }));
  return imageUrl;
}

//In the component where you want to display the image
async function displayImage() {
  const imageUrl = await heicToPng(response.content); //assuming response is the object you received from API
  return (
    <img src={imageUrl} alt="Image" />
  );
}
In this code snippet, we are using the heic-convert library to convert the HEIC file to PNG and then converting it to a base64 encoded string which can be used as the src of the img tag. You can modify this code to convert to other formats supported by the heic-convert library like JPEG.
;