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
>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()))