Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flask uploaded file size is not correct

Why flask’s uploaded file byte length is shorter than what it is actually? I’m seeing same behavior for several images.

from flask import Flask

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
    if request.method == 'POST':
        f = file.read()
        print(len(f))  # 45825

However,

f = skimage.io.imread('file.jpg')
len(f.tobytes())  # 1102080

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you upload an image using Flask, it reads the file’s content as a bytestring, which represents the size of the compressed image file. However, when reading the image with skimage.io.imread(‘file.jpg’), it’s read into a NumPy array, representing the uncompressed image data. So I think you’re seeing the compression rate.

To compare the sizes fairly, you can convert the uploaded bytestring to a NumPy array without saving it to disk:

import io
from PIL import Image
import numpy as np
from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
    if request.method == 'POST':
        file = request.files['file']
        f = file.read()
        print(len(f))

        # Convert the bytestring to a NumPy array
        image = Image.open(io.BytesIO(f))
        image_np = np.array(image)
        print(len(image_np.tobytes()))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading