Skip to content
Advertisement

LookupError: ‘base64’ is not a text encoding; use codecs.decode() to handle arbitrary codecs

Its showing error LookupError: ‘base64’ is not a text encoding; use codecs.decode() to handle arbitrary codecs.

Last few lines when the execution stops are – thumbnail = resize(photo_data, 200, 200) File “/home/anurag/photoshare/app.py”, line 406, in resize image_string = StringIO(img.decode(‘base64’)) LookupError: ‘base64’ is not a text encoding; use codecs.decode() to handle arbitrary codecs

begin photo uploading code

photos uploaded using base64 encoding so they can be directly embeded in HTML

ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
def allowed_file(filename):``
return '.' in filename and filename.rsplit('.', 1)[1] in 
ALLOWED_EXTENSIONS

@app.route('/upload', methods=['GET', 'POST'])
@flask_login.login_required
def upload_file():
if request.method == 'POST':
    uid = getUserIdFromEmail(flask_login.current_user.id)
    imgfile = request.files['photo']
    caption = request.form.get('caption')
    album_id = request.form.get('album')
    tags = request.form.get('tags')
    photo_data = base64.standard_b64encode(imgfile.read())
    thumbnail = resize(photo_data, 200, 200)
    cursor = conn.cursor()
    cursor.execute("INSERT INTO Photos (imgdata, thumbnail, user_id, 
caption, album_id) VALUES ('{0}', '{1}', '{2}', '{3}', 
'{4}')".format(photo_data, thumbnail, uid, caption, album_id))
    conn.commit()
    picture_id = cursor.lastrowid
    print (picture_id)
    print (tags)
    insert_tags(picture_id, tags)
    return redirect( url_for('get_album', id=album_id))
#The method is GET so we return a  HTML form to upload the a photo.
else:
    return render_template('upload.html', loggedin=True, 
albums=get_all_album_data())

end photo uploading code

resizes if greater than (x,y) else returns original

def resize(img, x,y):
image_string = StringIO(img.decode('base64'))
with Image.open(image_string) as image:
    if image.size[0] > 200 and image.size[1] > 200:
        cover = resizeimage.resize_cover(image, [x,y])
        buffer = StringIO()
        cover.save(buffer, format="JPEG")
        return base64.b64encode(buffer.getvalue())
    else:
        return img

Then there is another filefor image. from PIL import Image from io import StringIO from resizeimage import resizeimage import os, base64

 def resize(img, x,y):
image_string = StringIO(img.decode('base64'))
``with Image.open(image_string) as image:
    if image.size[0] > 200 and image.size[1] > 200:
        cover = resizeimage.resize_cover(image, [x,y])
        return base64.standard_b64encode(cover)
    else:
        return img``

Advertisement

Answer

You should import base64 instead of decoding the img with img.decode

base64.decodestring(img)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement