Issue
in my flask app after receiving POST request and running the code
image = request.files['image']
image variable have type <FileStorage: 'image.png' ('image/png')>
how can i convert it to Pillow image or open with Image.open() ?
Solution
FileStorage
is not image type but only wrapper on normal files like PNG/JPG/PDF/Excel/etc.
which flask uses to keep information about original files and which gives you direct access to original file - probably as file handler
- and Pillow can use it directly to read image (without saving to file, and without using io.Bytes
to create file image in memory)
image = request.files['image']
img = Image.open(image) # load with Pillow
print(img.size) # show image size (width, height)
img = img.convert('L') # convert to greyscale
img.save('output.png') # save it
#draw = ImageDraw.Draw(img) # create object to draw figures or text on image
All modules/functions which can use file handler
instead of filename
(to read file) should read from FileStorage
without problem.
EDIT:
Minimal working code - tested with images .png, .jpg, .webp
from flask import Flask, request, render_template_string
from PIL import Image
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
print(request.files)
if request.files:
image = request.files['image']
# pillow
img = Image.open(image)
print(img.size)
img = img.convert('L') # greyscale
img.save('output.png')
return render_template_string('''<form method="POST" enctype="multipart/form-data">
<input type="file" name="image"/>
<button type="submit">Submit</button>
</form>''')
if __name__ == '__main__':
app.run(debug=True)
Answered By - furas
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.