簡體   English   中英

如何在Python中找到base64編碼圖像的文件擴展名

[英]How to find file extension of base64 encoded image in Python

我有一個 base64 編碼的圖像,我將其解碼並保存到 Django 中的 ImageField 中。 我想給文件一個隨機名稱,但我不知道文件擴展名。

我在字符串前面加上了“data:image/png;base64”,我知道我可以做一些正則表達式來提取 mimetype,但我想知道是否有最佳實踐方法可以從“data:image” /png;base64," 到 ".png" 可靠。 當有人突然想要上傳我不支持的奇怪圖像文件類型時,我不想讓我的手動功能中斷。

最佳做法是檢查文件的內容,而不是依賴文件外部的內容。 例如,許多電子郵件攻擊依賴於錯誤識別 mime 類型,以便毫無戒心的計算機執行它不應該執行的文件。 幸運的是,大多數圖像文件擴展名可以通過查看前幾個字節(在解碼 base64 之后)來確定。 但是,最佳實踐可能是使用文件魔法,它可以通過 python 包訪問,例如this onethis one

大多數圖像文件擴展名在 mimetype 中是顯而易見的。 對於 gif、pxc、png、tiff 和 jpeg,文件擴展名就是 mime 類型的“image/”部分之后的任何內容。 為了處理晦澀的類型,python 確實提供了一個標准包:

>>> from mimetypes import guess_extension
>>> guess_extension('image/x-corelphotopaint')
'.cpt'
>>> guess_extension('image/png')
'.png'

看起來mimetypes stdlib 模塊即使在 Python 2 中也支持數據 url:

>>> from mimetypes import guess_extension, guess_type
>>> guess_extension(guess_type("data:image/png;base64,")[0])
'.png'

假設 base64 編碼在變量encoded_string ,下面的代碼對我encoded_string

from base64 import b64decode
import imghdr

encoded_string = 'image base64 encoded'

decoded_string = b64decode(var)
extension = imghdr.what(None, h=decoded_string)

您可以使用 mimetypes 模塊 - http://docs.python.org/2/library/mimetypes.html

基本上mimetypes.guess_extension(mine)應該可以完成這項工作。

我在 Lambda 中編寫了代碼,它會查找圖像的類型並檢查 base64 是否為圖像。

以下代碼肯定會幫助某人。

import base64
import imghdr
def lambda_handler(event, context):
    image_data = event['img64']    # crate "json event" in lambda 
                                   # Sample JSON Event ========>  { "img64" : BASE64 of an Image }
                                   # Get BASE64 Data of image in image_data variable.
    sample = base64.b64decode(image_data)      # Decode the base64 data and assing to sample.

    for tf in imghdr.tests:
        res = tf(sample, None)
        if res:
            break;
    print("Extension OR Type of the Image =====>",res)
    if(res==None): # if res is None then BASE64 is of not an image.
            return {
            'status': 'False',
           'statusCode': 400,
           'message': 'It is not image, Only images allowed'
          }
    else:
        return 'It is image'  

注意:-以上代碼是用python編寫的Lambda(AWS),您可以將以下代碼復制並粘貼到您的本地機器並進行如下測試。

import base64
import imghdr
image_data = "BASE64 OF AN IMAGE"
sample = base64.b64decode(image_data)      # Decode the base64 data and     assing to sample.

for tf in imghdr.tests:
    res = tf(sample, None)
    if res:
        break;
print("Extension OR Type of the Image =====>",res)
if(res==None):
    print('It is not image, Only images allowed')
else:
    print('It is image')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM