Django使用Piexif更新InMemoryUploadedFile

问题描述

我试图在上传的图像上剥离exif数据,然后再继续对其进行其他处理,然后再保存到服务器。

我正在使用this answer中的piexif来去除exif元数据。但是,piexif.insert() documentation需要修改图像的路径。 piexif可以用于写入内存中的文件吗?

还记录了PIL以去除exif数据。由于无论如何我都在使用PIL,所以我宁愿使用纯PIL方法

def modifyAndSaveImage():
    # Get the uploaded image as an InMemoryUploadedFile
    i = form.cleaned_data['image']

    # Use piexif to remove exif in-memory?
    #exif_bytes = piexif.dump({})
    #piexif.insert(exif_bytes,i._name)  # What should the second parameter be?

    # continue using i...
    im = Image.open(i)
    buffer = BytesIO()
    im.save(fp=buffer,format='JPEG',quality=95)

    return ContentFile(buffer.getvalue())

PIL的保存方法似乎是将exif数据应用于图像,而不是不使用exif进行保存(将旋转应用于原始图像)。还是这是由BytesIO缓冲区引起的?

解决方法

如果您使用PIL加载文件并保存,它将去除EXIF;

from PIL import Image

image = Image.open(form.cleaned_data['image'])

image.save('my_images/image.jpg')

如果仍然存在任何数据问题,您也可以尝试创建一个全新的图像;

from PIL import Image

image = Image.open(form.cleaned_data['image'])

image_data = list(image.getdata())

new_image = Image.new(image.mode,image.size)
new_image.putdata(image_data)
new_image.save('my_images/image.jpg')
Image上的

docs是here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...