preprocess avatar when uploading

pull/2/head
radex 2023-10-14 15:51:18 +02:00
parent e01267c49f
commit fede3f68e5
2 changed files with 23 additions and 11 deletions

View File

@ -70,6 +70,12 @@ def resize_image(image: Image, length: int) -> Image:
# We now have a length*length pixels image.
return resized_image
def process_upload(data: bytes) -> bytes:
img = Image.open(io.BytesIO(data))
img = resize_image(img, 256)
res = io.BytesIO()
img.save(res, 'PNG')
return base64.b64encode(res.getvalue())
syrenka = Image.open("syrenka.png")

View File

@ -1,17 +1,12 @@
import ldap
import flask
import flask_wtf
import io
import base64
from webapp import app, context, config, validation
from webapp import app, context, config, validation, avatar
from webapp.auth import login_required
bp = flask.Blueprint('vcard', __name__)
def str_to_ldap(s):
return s.encode('utf-8')
perm_errors = {
'add': 'You cannot add this attribute!',
'mod': 'You cannot change this attribute!',
@ -54,16 +49,27 @@ def attr_op(op, attrName, uid = None, success_redirect='/vcard',
op = 'mod'
new_value = ''
else:
op = 'mod'
new_value = base64.b64encode(new_value.read()).decode('utf-8')
try:
op = 'mod'
processed_avatar = avatar.process_upload(new_value.read())
new_value = processed_avatar
print(f'Uplading avatar (size: {len(processed_avatar)}) for {dn}')
except Exception as e:
flask.flash('Could not process avatar: {}'.format(e), 'danger')
return flask.redirect(fatal_redirect)
def to_ldap(s):
if isinstance(s, bytes):
return s
return s.encode('utf-8')
if op in ['del', 'modreadd']:
conn.modify_s(dn, [(ldap.MOD_DELETE, attrName, str_to_ldap(old_value))])
conn.modify_s(dn, [(ldap.MOD_DELETE, attrName, to_ldap(old_value))])
if op in ['add', 'modreadd']:
conn.modify_s(dn, [(ldap.MOD_ADD, attrName, str_to_ldap(new_value))])
conn.modify_s(dn, [(ldap.MOD_ADD, attrName, to_ldap(new_value))])
if op in ['mod']:
conn.modify_s(dn, [(ldap.MOD_REPLACE, attrName, str_to_ldap(new_value))])
conn.modify_s(dn, [(ldap.MOD_REPLACE, attrName, to_ldap(new_value))])
context.refresh_profile()
return flask.redirect(success_redirect)