Skip to content
Advertisement

Is there any way to check a image size before uploading in react native?

I am currently using image picker and image manipulator in my project for uploading and compressing the image. But I want to show user that he cannot upload image greater than any particular size(let’s say 5mb). How can I achieve this in react- native?

Advertisement

Answer

I’m actually doing this exact thing with ImagePicker in my app. Here’s how I do it:

const result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: "Images",
    allowsEditing: true,
    base64: true,
    quality: 1,
});

if (!result.cancelled) {
    const fileSize = result.base64.length * (3 / 4) - 2;
    if (fileSize > 6000000) {
        setFileSizeError(true);
    } else {
        setFileSizeError(false);
        const base64 = `data:image/png;base64,${result.base64}`;
        await dispatch(myExampleAction(base64));
    }
}

File size is calculated by the function -your base64 string length- * (3 / 4) - 2. Where at the end - 2 depends on how many == your base64 is trailed by. For example just one = would be - 1 instead.

Also fileSizeError is set by setFileSizeError. And will switch the boolean if it’s bigger than 6000000 bytes.

5 People found this is helpful
Advertisement