常量我=新图像();不适用于 react-native iOS 和 Android

const i = new Image(); does not work on react-native iOS and Android

我在 react-native 中遇到以下错误:

[Unhandled promise rejection: ReferenceError: Can't find variable: Image]
* src/utils/b64ToBlob.js:45:56 in Promise$argument_0

这是在 b64ToBlog.js 中失败的函数:

export const getImageDimensions = (file) => new Promise((resolved) => {
  const i = new Image();
  i.onload = () => resolved(i);
  i.src = file;
});

iOSAndroid 上,它在 const i = new Image(); 上失败:

如何提供 Image 或从 URL 获取图像尺寸,或者如何在 react-native 中提供 Image

编辑

对于那些感兴趣的人,这是我的最终解决方案:

import { Platform, Image as ImageNative } from 'react-native';

export const getImageDimensions = (file) => new Promise((resolved) => {
  if (Platform.OS === 'web') {
    const i = new Image();
    i.onload = () => resolved(i);
    i.src = file;
    return i;
  } else {
    return getSizeNative(file).then(resolved);
  }
});

function getSizeNative(uri) {
  return new Promise((resolve, reject) => {
    ImageNative.getSize(uri, (width, height) => resolve({ width, height }), reject)
  })
}

您显示的代码适用于 DOM Image constructor, not React Native's Image component

查看 API ,看起来 React Native 的 Image 组件提供了一个 getSize static method:

import { Image } from "react-native";

export const getImageDimensions = (file) => new Promise((resolved, reject) => {
    Image.getSize(
        file,
        (width, height) => resolve({width, height}),
        reject
    );
});

遗憾的是,文档似乎没有说明如何将大小报告给成功函数,因此您可能需要更深入地研究或尝试一下,看看会得到什么。 ...但是从问题中随后发布的代码来看,它似乎将它们作为离散参数接收,所以我更新了上面的内容。