英文:
Flask uploaded file size is not correct
问题
Flask的上传文件字节长度比实际长度要短,对于多个图像都出现了相同的行为。
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
然而,
f = skimage.io.imread('file.jpg')
len(f.tobytes()) # 1102080
英文:
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
答案1
得分: 1
当您使用Flask上传图像时,它将文件的内容读取为一个字节字符串,表示压缩后的图像文件的大小。然而,当使用skimage.io.imread('file.jpg')读取图像时,它会读取为一个NumPy数组,表示未压缩的图像数据。所以我认为您看到的是压缩比率。
为了公平比较大小,您可以将上传的字节字符串转换为NumPy数组,而无需将其保存到磁盘上:
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))
# 将字节字符串转换为NumPy数组
image = Image.open(io.BytesIO(f))
image_np = np.array(image)
print(len(image_np.tobytes()))
英文:
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()))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论