如何在 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 编码图像的文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)