You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中使用Image.getSize()获取图片尺寸失败的问题求助

解决React Native中Image.getSize()无法获取Google Books图片尺寸的问题

问题分析

你遇到的Failed to get size for image警告,核心原因是Image.getSize()的请求策略和直接加载图片的Image组件不一致:Google Books的图片服务可能对请求头、防盗链规则有限制,getSize()的请求触发了这些限制,但实际加载图片的请求却能通过,导致图片可正常显示但尺寸获取失败。

解决方案

改用Image实例的onLoad事件获取尺寸

放弃Image.getSize(),通过创建临时Image实例并监听onLoad事件的方式获取尺寸,这种方式和实际加载图片的行为完全一致,能避开大部分服务器限制:

// 封装获取图片尺寸的工具函数
const getImageDimensions = (uri) => {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.onload = () => {
      resolve({ width: image.width, height: image.height });
    };
    image.onerror = (error) => {
      reject(new Error(`加载图片失败: ${error.message}`));
    };
    image.src = uri;
  });
};

// 替换原有搜索逻辑中的尺寸获取代码
const handleIsbnSearch = async () => {
  const books = await isbnSearch(isbn);
  if (books.error) {
    return setBookSearch([]);
  }
  let bookInfo = [];
  for (let b in books) {
    const volInfo = books[b].volumeInfo;
    try {
      const { width, height } = await getImageDimensions(volInfo.imageLinks.thumbnail);
      const aspectRatio = width / height;
      bookInfo.push({
        title: volInfo.title,
        subtitle: volInfo.subtitle,
        authors: volInfo.authors,
        publisher: volInfo.publisher,
        publishedDate: volInfo.publishedDate,
        description: volInfo.description,
        categories: volInfo.categories,
        thumbnail: volInfo.imageLinks.thumbnail,
        aspectRatio: aspectRatio
      });
    } catch (err) {
      // 单个图片获取失败时不中断循环,给默认宽高比兜底
      console.warn(`无法获取图片尺寸: ${volInfo.imageLinks.thumbnail}`, err);
      bookInfo.push({
        title: volInfo.title,
        subtitle: volInfo.subtitle,
        authors: volInfo.authors,
        publisher: volInfo.publisher,
        publishedDate: volInfo.publishedDate,
        description: volInfo.description,
        categories: volInfo.categories,
        thumbnail: volInfo.imageLinks.thumbnail,
        aspectRatio: 1 // 默认正方形比例
      });
    }
  }
  setBookSearch(bookInfo);
};

额外排查点

  • Android网络权限:检查AndroidManifest.xml是否添加了<uses-permission android:name="android.permission.INTERNET" />,确保应用有网络访问权限。
  • iOS ATS配置:确认Info.plist中未限制HTTPS请求(默认允许,若手动修改过需检查)。

内容的提问来源于stack exchange,提问作者wrentfree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 22:09:50