“Flask上传的文件大小不正确”

huangapple go评论68阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年5月6日 23:35:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76189730.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定