如何在Python中找到base64编码图像的文件扩展名 [英] How to find file extension of base64 encoded image in Python

查看:792
本文介绍了如何在Python中找到base64编码图像的文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个base64编码的图像,我将其解码并保存到Django中的ImageField中.我想给文件取一个随机的名字,但是我不知道文件的扩展名.

I have a base64 encoded image that I decode and save into an ImageField in Django. I want to give the file a random name, but I don't know the file extension.

我在字符串前添加了"data:image/png; base64",我知道我可以做一些正则表达式来提取mimetype,但是我想知道是否有一种最佳做法可以从"data:image/png; base64"到".png"可靠.当有人突然想上传一个我不支持的奇怪图像文件类型时,我不想中断手动功能.

I have "data:image/png;base64," prepended to the string and I know I could do some regex to extract the mimetype, but I'd like to know if there is a best practices way to go from "data:image/png;base64," to ".png" reliably. I don't want to have my handspun function break when someone suddenly wants to upload a strange image filetype that I don't support.

推荐答案

最佳做法是检查文件的内容,而不是依赖文件外部的内容.例如,许多电子邮件攻击依靠错误地识别mime类型,以便毫无戒心的计算机执行不应该执行的文件.幸运的是,大多数图像文件扩展名都可以通过查看前几个字节(在解码base64之后)来确定.不过,最佳做法可能是使用文件魔术,该魔术可以通过python软件包,例如

It is best practices to examine the file's contents rather than rely on something external to the file. Many emails attacks, for example, rely on mis-identifying the mime type so that an unsuspecting computer executes a file that it shouldn't. Fortunately, most image file extensions can be determined by looking at the first few bytes (after decoding the base64). Best practices, though, might be to use file magic which can be accessed via a python packages such as this one or this one.

大多数图像文件扩展名在mimetype中都是显而易见的.对于gif,pxc,png,tiff和jpeg,文件扩展名就是mime类型的"image/"部分之后的内容.为了处理晦涩的类型,python确实提供了一个标准包:

Most image file extensions are obvious from the mimetype. For gif, pxc, png, tiff, and jpeg, the file extension is just whatever follows the 'image/' part of the mime type. To handle the obscure types also, python does provide a standard package:

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

这篇关于如何在Python中找到base64编码图像的文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆