Fix resize of image on upload of Identity profile pics

This commit is contained in:
Michael Manfre 2022-11-20 13:18:14 -05:00 committed by GitHub
parent a43ccde8d9
commit 75e7385968
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -42,6 +42,13 @@ class ProfilePage(FormView):
"image": self.request.identity.image and self.request.identity.image.url, "image": self.request.identity.image and self.request.identity.image.url,
} }
def resize_image(self, image: File, *, size: tuple[int, int]) -> File:
with Image.open(image) as img:
resized_image = ImageOps.fit(img, size)
new_image_bytes = io.BytesIO()
resized_image.save(new_image_bytes, format=img.format)
return File(new_image_bytes)
def form_valid(self, form): def form_valid(self, form):
# Update identity name and summary # Update identity name and summary
self.request.identity.name = form.cleaned_data["name"] self.request.identity.name = form.cleaned_data["name"]
@ -50,14 +57,14 @@ class ProfilePage(FormView):
icon = form.cleaned_data.get("icon") icon = form.cleaned_data.get("icon")
image = form.cleaned_data.get("image") image = form.cleaned_data.get("image")
if isinstance(icon, File): if isinstance(icon, File):
resized_image = ImageOps.fit(Image.open(icon), (400, 400)) self.request.identity.icon.save(
new_icon_bytes = io.BytesIO() icon.name,
resized_image.save(new_icon_bytes, format=icon.format) self.resize_image(icon, size=(400, 400)),
self.request.identity.icon.save(icon.name, File(new_icon_bytes)) )
if isinstance(image, File): if isinstance(image, File):
resized_image = ImageOps.fit(Image.open(image), (400, 400)) self.request.identity.image.save(
new_image_bytes = io.BytesIO() image.name,
resized_image.save(new_image_bytes, format=image.format) self.resize_image(image, size=(400, 400)),
self.request.identity.image.save(image.name, File(new_image_bytes)) )
self.request.identity.save() self.request.identity.save()
return redirect(".") return redirect(".")