如何使用Python-PIL下载图像并提取Exif数据?

2024-06-15 08:02:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从下载的图像中读取Exif数据。我用一个函数将图像保存到我的计算机上,然后尝试在另一个函数中读取数据,但我一直收到坏模式错误。我已经能够从预先保存的图像中读取数据,并且刚刚使用了。\ u getexif(),但当我尝试对图像执行相同的操作时,我下载的图像却无法正常工作。我做错什么了?在

下面是调用这两个函数的循环。在

else:
    imgTags = findImages(url)
    for imgTag in imgTags:
        imgFileName = downloadImage(imgTag)
        testForExif(imgFileName)

从页面中查找并下载图像

^{pr2}$

读取exif数据

def testForExif(imgFileName):
    exifData = {}
    imgFile = Image.open(imgFileName, 'rb')
    info = imgFile._getexif()
    print '\n\n' + str(info) + '\n\n'
    if info:
        for (tag, value) in info.items():
            decoded = TAGS.get(tag, tag)
            exifData[decoded] = value
        exifGPS = exifData['GPSInfo']
        if exifGPS:
            print '[+] ' + imgFileName + ' contains GPS MetaData'

我相信‘bad mode’错误是在testsForExif函数中,在前几行的某个地方触发的。它永远不会出现在第一个print语句中。在

我得到的确切错误是。在

ValueError: Bad Mode

Traceback (most recent call last): File "C:\Users\HeyNow\Downloads\Python\Cookbook\Forensics\metaurl.py", line 59 , in main() File "C:\Users\HeyNow\Downloads\Python\Cookbook\Forensics\metaurl.py", line 56 , in main testForExif(imgFileName) File "C:\Users\HeyNow\Downloads\Python\Cookbook\Forensics\metaurl.py", line 31 , in testForExif imgFile = Image.open(imgFileName, 'rb') File "C:\Python27\lib\site-packages\PIL\Image.py", line 1947, in open raise ValueError("bad mode") ValueError: bad mode

从玩它我也得到了一个

Bad Mode 'rb', filename;

也有错误。在

我迷路了。在

编辑:如果我更改:

imgFile = Image.open(imgFileName, 'rb')

imgFile = Image.open(imgFileName)

我得到AttributeError: _getexif() 回溯:

Traceback (most recent call last): File "C:\Users\HeyNow\Downloads\Python\Cookbook\Forensics\metaurl.py", line 59 , in main() File "C:\Users\HeyNow\Downloads\Python\Cookbook\Forensics\metaurl.py", line 56 , in main testForExif(imgFileName) File "C:\Users\HeyNow\Downloads\Python\Cookbook\Forensics\metaurl.py", line 32 , in testForExif info = imgFile._getexif() File "C:\Python27\lib\site-packages\PIL\Image.py", line 512, in getattr raise AttributeError(name) AttributeError: _getexif


Tags: inpy图像imagedownloadslineusersfile
2条回答

您不需要太多definerb模式,只需使用:

Image.open(imgFileName)

唯一接受的模式是Image.open()模式(默认)。见here

我想你是因为“下载图片”的工作方式而出错的。如果出现任何类型的错误,则返回一个空字符串。但是,在testforexif中,在试图打开文件名之前,您不会检查文件名是否为空字符串。在

Image.open('') 

将导致imgfile为None。所以它没有属性,你会得到属性错误。在

在解析网页或处理引发错误的文件名时,可能存在某些错误。不正确地处理错误是非常糟糕的,在这种情况下,它会导致程序根本无法运行。您有try/except语句,但是即使有错误也可以继续。您需要做的是更改except子句,以便在出现错误(或文件名为null)时跳过该文件名。希望有帮助。在

编辑:

试着打印你的变量(比如文件名),以确保它们是正确的,并且图像是存在的。这也可能是文件类型的问题。例如,您的脚本可能正在查找一些非jpg图像文件,并试图打开bmp或其他文件上的exif数据。在

相关问题 更多 >