如何在 Python 中查找 base64 编码图像的文件扩展名

How to find file extension of base64 encoded image in Python(如何在 Python 中查找 base64 编码图像的文件扩展名)

本文介绍了如何在 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 之后).不过,最佳实践可能是使用 file magic 可以通过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 编码图像的文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 Python 中查找 base64 编码图像的文件扩展名

基础教程推荐