我正在尝试使用requests
保存我下载的图片,然后在模型中使用Pillow
修改为ImageField
。但是在没有图像的情况下创建对象。
这就是我所拥有的:
settings.py
MEDIA_ROOT = BASE_DIR + "/media/"
MEDIA_URL = MEDIA_ROOT + "/magicpy_imgs/"
models.py
def create_path(instance, filename):
path = "/".join([instance.group, instance.name])
return path
class CMagicPy(models.Model):
image = models.ImageField(upload_to=create_path)
....
# Custom save method
def save(self, *args, **kwargs):
if self.image:
image_in_memory = InMemoryUploadedFile(self.image, "%s" % (self.image.name), "image/jpeg", self.image.len, None)
self.image = image_in_memory
return super(CMagicPy, self).save(*args, **kwargs)
forms.py
class FormNewCard(forms.Form):
imagen = forms.URLField(widget=forms.URLInput(attrs={'class': 'form-control'}))
views.py
def new_card(request):
template = "hisoka/nueva_carta.html"
if request.method == "POST":
form = FormNewCard(request.POST)
if form.is_valid():
url_image = form.cleaned_data['imagen']
group = form.cleaned_data['grupo']
name = form.cleaned_data['nombre']
description = form.cleaned_data['descripcion']
answer = requests.get(url_image)
image = Image.open(StringIO(answer.content))
new_image = image.crop((22, 44, 221, 165))
stringio_obj = StringIO()
try:
new_image.save(stringio_obj, format="JPEG")
image_stringio = stringio_obj.getvalue()
image_file = ContentFile(image_stringio)
new_card = CMagicPy(group=group, description=description, name=name, image=image_file)
new_card.save()
finally:
stringio_obj.close()
return HttpResponse('lets see ...')
它创建对象但没有图像。请帮忙。我一直试图解决这个问题几个小时。
答案 0 :(得分:4)
虽然InMemoryUploadedFile主要供MemoryFileUploadHandler使用,但它也可用于其他目的。应该注意的是,MemoryFileUploadHandler用于处理用户使用webform或窗口小部件将文件上传到您的服务器时的情况。但是,您正在处理的情况是用户仅提供链接,并且下载文件到您的Web服务器上。
我们还记得ImageFile本质上是对存储在文件系统中的文件的引用。仅在文件夹中输入文件的名称,并且文件的内容本身存储在存储系统中。 Django允许您指定不同的存储系统,以便在需要时可以将文件保存在云端。
您需要做的就是将使用Pillow
生成的图片内容传递给ImageField
。该内容可以通过InMemoryUploaded
文件或 a ContentFile
发送。但是,不需要同时使用它们。
所以这是你的模特。
class CMagicPy(models.Model):
image = models.ImageField(upload_to=create_path)
# over ride of save method not needed here.
这是你的观点。
try:
# form stuff here
answer = requests.get(url_image)
image = Image.open(StringIO(answer.content))
new_image = image.rotate(90) #image.crop((0, 0, 22, 22))
stringio_obj = StringIO()
new_image.save(stringio_obj, format="JPEG")
image_file = InMemoryUploadedFile(stringio_obj,
None, 'somefile.jpg', 'image/jpeg',
stringio_obj.len, None)
new_card = CMagicPy()
new_card.image.save('bada.jpg',image_file)
new_card.save()
except:
# note that in your original code you were not catching
# an exception. This is probably what made it harder for
# you to figure out what the root cause of the problem was
import traceback
traceback.print_exc()
return HttpResponse('error')
else:
return HttpResponse('done')
添加了异常处理,因为事情可能会出错。
您应该使用answers.headers [' Content-type']而不是使用JPEG和image / jpeg,并选择合适的。
答案 1 :(得分:1)
试试这个self.image.save(some_file_path, ContentFile(image_stringio))
。在我看来,您不需要在模型中覆盖save()
。