Hugh
Hugh

Reputation: 366

Get image dimension from blob in React Native

Let's suppose I'm calling an API which serves images with random dimensions. I need to know the width and the height for each image before rendering, because I need to do some computations for the precise layout I want.

With Web Apis, I've made this and it's working fine:

const res = await fetch("https://picsum.photos/200/300");
const blob = await res.blob();
const img = new Image();
img.src = URL.createObjectURL(blob);
console.log(img.src);
img.onload = () => {
  console.log(img.width, img.height);
};

The problem is that with React Active, we don't have access to the Web Api Image Object. Image is a component on React Native.


Here's where I'm at:

const res = await fetch("https://picsum.photos/200/300");
const blob = await res.blob();

So basically the binary data is stored in RAM right now, but I can't find any way to interpret this data into an image and get the dimensions.

Upvotes: 1

Views: 1525

Answers (1)

redempt
redempt

Reputation: 51

React Native Image component has built-in getSize method. If you can transform your blob to URI than you can use the code below.

Image.getSize(myUri, (width, height) => { console.log(width, height)});

Upvotes: 2

Related Questions