Fixes avatar crop logic

This commit is contained in:
Mouse Reeve 2020-04-20 18:42:13 -07:00
parent b0493225be
commit 94e66829b8

View file

@ -84,24 +84,24 @@ def edit_profile(request):
request.user.name = form.data['name'] request.user.name = form.data['name']
if 'avatar' in form.files: if 'avatar' in form.files:
# crop and resize avatar upload # crop and resize avatar upload
original = Image.open(form.files['avatar']) image = Image.open(form.files['avatar'])
target_size = 120 target_size = 120
height, width = original.size width, height = image.size
scale = height / target_size if height < width else width / target_size thumbnail_scale = height / (width / target_size) if height > width \
resized = original.resize(( else width / (height / target_size)
int(height / scale), image.thumbnail([thumbnail_scale, thumbnail_scale])
int(width / scale) width, height = image.size
))
height, width = resized.size
cropped = resized.crop(( width_diff = width - target_size
int((width - target_size) / 2), height_diff = height - target_size
int((height - target_size) / 2), cropped = image.crop((
int(width - (width - target_size) / 2), int(width_diff / 2),
int(height - (height - target_size) / 2) int(height_diff / 2),
int(width - (width_diff / 2)),
int(height - (height_diff / 2))
)) ))
output = BytesIO() output = BytesIO()
cropped.save(output, format='JPEG') cropped.save(output, format=image.format)
ContentFile(output.getvalue()) ContentFile(output.getvalue())
request.user.avatar.save( request.user.avatar.save(
form.files['avatar'].name, form.files['avatar'].name,
@ -453,3 +453,4 @@ def import_data(request):
'failures': failures, 'failures': failures,
}) })
return HttpResponseBadRequest() return HttpResponseBadRequest()