python-3.x - 使用来自 URL 响应的 PIL 打开特定图像的问题
问题描述
我正在从 URL 中抓取图像并进行一些操作,然后将它们保存到磁盘。这适用于绝大多数图像,但尽管在浏览器中加载良好,但仍有某些图像 URL 失败。我查看了错误跟踪,但对这里的各种修复都没有运气。以下是提取为失败的示例 URL。
OSError: 无法识别图像文件 <_io.BytesIO object at...>
from PIL import Image
import requests
from io import BytesIO
urlString = "http://lcl3.com/chemStructures1/A-10400.JPG"
response = requests.get(urlString,headers={'User-Agent': 'Mozilla/5.0'},timeout=10)
img = Image.open(BytesIO(response.content)) #check that it is an image; fails here
rgb_im = img.convert('RGB')
basewidth = 450
wpercent = (basewidth/float(rgb_im.size[0]))
if float(rgb_im.size[0]) > 450:
hsize = int((float(rgb_im.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
rgb_im.save(image_folder / image_file_name,optimize=True,quality=95)
我认为该文件的格式不同。如需额外参考,该行在以下位置失败:
response = requests.get(urlString,headers={'User-Agent': 'Mozilla/5.0'},timeout=10)
并给出上述痕迹。我敢肯定它可能是一条线,但我把头发扯掉了,所以任何想法都会受到热烈的赞赏!
编辑:
我发现更多链接失败。例如
http://www.excelscientific.com/sealplate.jpg
https://www.bioexpress.com/stibo/web/std.lang.all/52/52/4695252.jpg
我查看了源代码,无法区分任何区别(这些页面上似乎没有任何“内容”只是图像,所以我越来越确信这是图像格式问题。
解决方案
推荐阅读
- javascript - javascript中的 Date(d.getTime()) 和 new Date(d.getTime()) 有什么区别?
- react-native - 带有选项卡导航的 react-native 抽屉导航
- sql - SQL中连续行之间的区别,包括第一行和最后一行?
- spring - 如果 Spring Boot 上不存在 Microsoft SQL Server 自动创建架构(application.properties)
- r - 执行模拟时如何指定结果的存储位置?
- c# - C# 裁剪没有 for 的二维数组
- scala - 从 SFTP 服务器递归下载目录内容
- regex - awk - 分配给变量的正则表达式 - 损坏
- ssis - 更新到 Visual Studio 2017 SSDT 后在 Visual Studio 2017 中使用脚本任务编辑器不再工作
- ruby - Ruby - 使用某些函数进行常量初始化会产生 NoMethodError