mrousavy / react-native-blurhash

🖼️ A library to show colorful blurry placeholders while your content loads.
https://blurha.sh
MIT License
1.98k stars 70 forks source link

[FEATURE] Handle non-image files gracefully with Blurhash.encode #189

Open ChristopherGabba opened 7 months ago

ChristopherGabba commented 7 months ago

Problem

If you feed a non-image file into Blurhash.encode:

const nonImage = 'file:///path/to/random.mp4`;
const blurhash = await Blurhash.encode(nonImage, 4, 3);

The app completely crashes with no error logs. Threw me for a loop for a few hours until I pinpointed the crash and problem with my code.

Solution

Ideally if you feed a non-image file into the blurhash.encode it should check first if it is a valid image and then throw a console.error if it isn't, instead of crashing the app with no logs.

Describe alternatives you've considered I added the following function:

import * as mime from "react-native-mime-types"

export async function isValidImage(url: string) {
/*
For some reason on Android, fetch - blob doesn't work and returns no mimetype, but it works on iOS
In order to check on android, use the mime.lookup(url) which coincidentally only works on Android and not iOS
*/
  try {
    const response = await fetch(url)
    const blob = await response.blob()
    return blob.type.startsWith("image/") || mime.lookup(url).toString().startsWith("image")
  } catch (error) {
    console.error("Blurhash doesn't work for files that aren't images!")
    return false
  }
}
mrousavy commented 7 months ago

Good feature request 👍

This should be simple to add in the native code, unfortunately I don't have any free time for such enhancements right now.