flask - send gzipped image

45 Views Asked by At

below you can find my old code (working) and my new code (not working). problem with the old code is that the images are 500 kb each and are provided while scrolling (lazy loading), so use up a lot of bandwith. The goal is to send the images gzipped, and have them unzip automatically by the browser, just like a gzipped webpage... how can I send a image compressed, so that when I load the url /getLogImage/?fn=123.jpg i see the actual file in the browser?

Old code:

@app.route('/getLogImage/')
def getLogImage():
    try:
        fileName = request.args.get('fn', None)
        return send_file("D:/images/" + fileName, mimetype='image/jpg')
    except Exception as err:
        return str(err)

New code:

@app.route('/getLogImage/')
def getLogImage():
    try:
        fileName = request.args.get('fn', None)

        # Read the original image file
        with open("D:/images/" + fileName, 'rb') as file:
            image_data = file.read()

        # Compress the image data using gzip
        compressed_image_data = gzip.compress(image_data, 9)

        return send_file(
            compressed_image_data,
            mimetype='image/jpeg',
            as_attachment=True,
            download_name='image.jpg.gz'
        )

    except Exception as err:
        return str(err)
0

There are 0 best solutions below