我正在尝试将图片尺寸调整为124 * 124。我进行了大量搜索,找到了相关问题的一些解决方案。但是我的问题仍然没有解决。
我的模特
class MyUsers(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,
related_name='user')
image = models.FileField(upload_to='static/photo', blank=True)
name = models.CharFiled(max_length=150)
def __str__(self):
return self.name
我的观点
def change_user_photo(request, id):
if request.method == "POST":
new_pic = request.FILES['new']
if new_image:
my_user = MyUser.objects.get(id=id)
image = Image.open(new_pic)
image = image.resize((124,124), Image.ANTIALIAS)
my_user.image = image
my_user.save()
return HttpResponseRedirect(reverse('my_profile'))
else:
user = get_photo(id)
return render(request, "photo/edit.html",
{"users":user})
我的模板:
<form method="POST" enctype="multipart/form-data" id="formUpload">
{% csrf_token %}
<div class="form-group">
<label>New Photo:</label>
<input type="file" name="new"/>
</div>
<hr/>
<div class="form-group">
<button type="submit" class="btn btn-sm btn-
success">Update</button>
</div>
</form>
答案 0 :(得分:2)
image = models.FileField()仅采用Fileupload对象,而您正在传递image对象。
def image_resize(self, field):
if field:
image = Img.open(field)
image = image.convert('RGB')
image = image.resize((800, 800), Img.ANTIALIAS)
output = io.BytesIO()
image.save(output, format='JPEG', quality=85)
output.seek(0)
return InMemoryUploadedFile(output, 'ImageField',
field.name,
'image/jpeg',
sys.getsizeof(output), None)
else:
return None
InMemoryUploadedFile在django.core.files.uploadedfile中可用。转换fileupload对象中的图像