mikeboers / flask-images Goto Github PK
View Code? Open in Web Editor NEWOn-demand resizing of images for Flask applications.
Home Page: https://mikeboers.github.io/Flask-Images/
License: BSD 3-Clause "New" or "Revised" License
On-demand resizing of images for Flask applications.
Home Page: https://mikeboers.github.io/Flask-Images/
License: BSD 3-Clause "New" or "Revised" License
There are so many bugs still left when using with python3,such as urllib bugs ,StringIO
This URL is being used by my system.
Its providing a broken image.
But if I go directly to the target URL, it is ok.
I faced this a few days ago, and solved by erasing all the /tmp folder.
Can I know which file to erase? Or do you think this can be fixed programatically?
I can send you my hole /tmp folder, if needed.
Lovato
Creating this issue just to not continue the discussion about travis in an unrelated issue #7.
Here, how to use PIL on travis: https://github.com/gabriel-ozeas/pyNES/blob/master/.travis.yml
I want to add some folders to IMAGES_PATH
, but don't want all files exposed.
I'm thinking about something like:
IMAGES_PATH = [("/my/static", "*allowed*"), "/static"]
# or
IMAGES_PATH = ["/my/static/*allowed*", "/static"]
This way, I'll expose /my/static/allowed.png
, but not /my/static/private.png
. It is easy to implement it and I have a perfect use case for this feature.
Of course I can just extend and hack the find_img
, but I'm looking for a better API.
Do you think it is useful for the project?
I am trying to fetch an image from GoogleMaps static api.
I faced 2 problems:
a) first, I had to replace '&' for '&' ... thats ok.
b) I got 'key error' at this point:
(u'http://maps.googleapis.com/maps/api/staticmap?markers=color:red|-29.828736,-51', u'.150409&zoom=17&size=600x600')
It is spliting for '.', and getting the 2nd part as extension, which in this case produces an error. The used URL was:
The error happens on line:
hashlib.md5(remote_url).hexdigest() + os.path.splitext(remote_url)[1]
The solution I found was:
http://imagebox.lovato.geek42.org/imgsizer/remote?w=300&u=http://maps.googleapis.com/maps/api/staticmap?markers=color:red%7C-29.828736,-51.150409%26zoom=17%26size=600x600%26ext=.jpg
By adding a ext fake parameter to my external URL, I succeeded.
I am getting this error when trying to initialize Flask-Images.
app = Flask(__ name __)
app.secret_key = 'secretkeythatyouneverguess'
images = Images(app)
Have no idea why. Tried to google it but not any solution for that.
here is the full error statement:
File "./run.py", line 3, in
from app import app
File "/home/proj/app/__ init __.py", line 15, in
images = Images(app)
File "/home/proj/flask/local/lib/python2.7/site-packages/flask_images.py", line 54, in __ init __
self.init_app(app)
File "/home/proj/flask/local/lib/python2.7/site-packages/flask_images.py", line 70, in init_app
app.add_template_global(resized_img_src)
AttributeError: 'Flask' object has no attribute 'add_template_global'
When I include my gif using url_for('static', filename='loading.gif')
, the animation and the transparency work as expected, but they stop working when I use Flask-Images' url_for('images', filename='loading.gif', height=50 )
. Flask-Images does successfully resize the image, though.
Testing with this gif:
How could I serve cached images as static files with nginx (or another webserver) after they was generated? Is it possible with Flask-Images ?
This may be a weird issue, but I'm kind of confused how to use this plugin. I loaded it by doing this:
from flask_images import Images
Images(app)
I then tried transforming this (withinin a template):
<img src="{{ url_for('static', filename='have-a-nice-day.jpg') }}">
into this:
<img src="{{ resized_img_src('static', filename='have-a-nice-day.jpg', width=50) }}">
but that results in the following url, which doesn't return anything
<img src="/imgsizer/static?filename=have-a-nice-day.jpg&w=50&s=Fw0kPelkfO6usnzyiGGZ87aYmws">
I tried some other variations, such as the ones below. But I can't get it to work:
<img src="{{ url_for('static', filename='have-a-nice-day.jpg', width=50) }}">
<img src="{{ url_for('static.crop', filename='have-a-nice-day.jpg', width=50) }}">
Could anybody help me out in how I should get this to work? All tips are welcome!
Hi, Do you know how to delete the cached image from the cache folder? when the original file is deleted, I need to delete the cached image
Thanks
I'm running Python 3.5.2 on Linux Mint 18.2
Traceback (most recent call last):
File "run.py", line 6, in <module>
from app import app
File "/home/kris/projects/soul/app/__init__.py", line 6, in <module>
from flask_images import Images
File "/home/kris/.virtualenvs/soul/lib/python3.5/site-packages/flask_images/__init__.py", line 1, in <module>
from .core import Images, resized_img_src, resized_img_size, resized_img_attrs, resized_img_tag
File "/home/kris/.virtualenvs/soul/lib/python3.5/site-packages/flask_images/core.py", line 3, in <module>
from cStringIO import StringIO
ImportError: No module named 'cStringIO'
Quote from SO question related to the problem:
The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.
It is the way Flask do the magic.
url_for('images.resize', filename='/path/to/file.png', width=80)
You can even define the mode
based on routes: images.fit
, images.crop
, ...
It is good because I can migrate from url_for('static', filename='/path/to/file.png')
in a really easy way.
It would be swell if we could predict the final width/height of an image so that they can be used in the template as well (to avoid a jump in layout when the images load).
Perhaps something like:
{{ resized_img('path/to/image.jpg', class_="myclass", mode='fit', width=200, height=200) }}
would render into:
<img class="myclass" src="/imgsizer/path/to/image.jpg?m=fit&w=200&h=200&s=xxx" width="200" height="150" />
Some testing needs to be done with regards to the speed at which dimension data can be extracted from images on disk without loading all of the data, so that we know if we can get away with the naive implementation or if we have to intelligently cache dimensions.
Is it possible to tell flask-images to honor jpeg exif orientation?
I have an application where users can upload images that are displayed resized by flask-images. But the exif orientation is not respected, so images show with the wrong orientation.
If I'm not mistaken, pillow can do it, but I couldn't find a hook to include this feature in flask-images.
Did I miss something?
GAE does not accept any python package that needs to be compiled.
And Flask-Images meets that requirement.
But F-I uses File I/O, which is not allowed inside GAE.
I can help with this one, but need to know first if you are already working in something like this... Or what would be the best approach. Get tied to some GAE offering (like https://developers.google.com/appengine/docs/java/googlecloudstorageclient/) or make it all-in-memory.
Best
Marco
This is a frequent configuration error, and is easily detected.
Flask-Images is not compatible with itsdangerous Version 2.0.0: https://itsdangerous.palletsprojects.com/en/2.0.x/changes/
I got this error when I tried to run my flask app:
Error: While importing 'app', an ImportError was raised:
Traceback (most recent call last):
File "/home/rof/.pyenv/versions/3.7/lib/python3.7/site-packages/flask_images/core.py", line 31, in <module>
from itsdangerous import Signer, constant_time_compare
ImportError: cannot import name 'constant_time_compare' from 'itsdangerous' (/home/rof/.pyenv/versions/3.7/lib/python3.7/site-packages/itsdangerous/__init__.py)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/rof/.pyenv/versions/3.7/lib/python3.7/site-packages/flask/cli.py", line 256, in locate_app
__import__(module_name)
File "/home/rof/src/github.com/shuttle99ou/misolvencia/app.py", line 7, in <module>
from domain_dispatcher import DomainsDispatcher
File "/home/rof/src/github.com/shuttle99ou/misolvencia/domain_dispatcher.py", line 2, in <module>
from MiSolvenciaApp.url_redirect import url_redirect, update_redirect_cache
File "/home/rof/src/github.com/shuttle99ou/misolvencia/MiSolvenciaApp/__init__.py", line 6, in <module>
from MiSolvenciaApp.utils.flask_image_resizer import Images
File "/home/rof/src/github.com/shuttle99ou/misolvencia/MiSolvenciaApp/utils/flask_image_resizer.py", line 4, in <module>
from flask_images import Images as FlaskImages
File "/home/rof/.pyenv/versions/3.7/lib/python3.7/site-packages/flask_images/__init__.py", line 1, in <module>
from .core import Images, resized_img_src, resized_img_size, resized_img_attrs, resized_img_tag
File "/home/rof/.pyenv/versions/3.7/lib/python3.7/site-packages/flask_images/core.py", line 34, in <module>
from itsdangerous._compat import constant_time_compare
ModuleNotFoundError: No module named 'itsdangerous._compat'
Please, validate this.
When opening this, https://pbs.twimg.com/media/Bq1dN3lIEAAgQbv.jpg, a 800px wide image, I got on chrome inspect a 33.2k size.
If I pass it through FlaskImages, default quality (75), and ask for 800 px as width output, I got a 33.7k size.
I am doing imgsizer/remote?w=800&u=https://pbs.twimg.com/media/Bq1dN3lIEAAgQbv.jpg
What do you think if FlaskImages, after generating the final file, knowing that the original is smaller, deliver and cache the original, as if it was generated by itself.
I know it depends on the original image, but it did happen sometimes.
Best
Lovato
I now have flask_images working flawlessly for static images with the following code:
{{ url_for('images', filename='have-a-nice-day.jpg', width=50) }}
I now want to use it for my dynamic document endpoint which gets images from a MongoDB instance. It is defined in Flask like this:
@app.route('/doc/<docId>')
def getDoc(docId):
userDoc = UserDocument.objects(id=docId).first()
if not userDoc:
return abort(404)
return Response(userDoc.file_.read(), mimetype=userDoc.file_.content_type)
So normally I create urls for an image using getDoc like this;
{{ url_for('getDoc', docId='8eb1796c-73b3-4398-855e-bfbfa02685d4') }}
How would I convert this to use flask_images for resizing? All tips are welcome!
got error message:
File "/home/ubuntu/.py3/lib/python3.6/site-packages/flask_images/core.py", line 492, in resized_img_tag
return '<img %s/>' % ' '.join('%s="%s"' % (k, cgi.escape(str(v))) for k, v in sorted(attrs.iteritems()))
AttributeError: 'dict' object has no attribute 'iteritems'
Hi, I am new to flask, and i want to use flask image to resize my image, i have follow all the step.
but i have problem with IMAGES_URL i use the default one (imgsizer). when i run my web app, i can not get the resize image. i use firebug to check it said fail to load url.
Please help me , what i am doing wrong?
Traceback (most recent call last):
File "manage.py", line 13, in
from flask.ext.images import Images
File "/home/Projects/venv/lib/python3.4/site-packages/flask/exthook.py", line 81, in load_module
reraise(exc_type, exc_value, tb.tb_next)
File "/home/Projects/venv/lib/python3.4/site-packages/flask/_compat.py", line 32, in reraise
raise value.with_traceback(tb)
File "/home/Projects/venv/lib/python3.4/site-packages/flask_images/init.py", line 1, in
from .core import Images, resized_img_src, resized_img_size, resized_img_attrs, resized_img_tag
File "/home/Projects/venv/lib/python3.4/site-packages/flask_images/core.py", line 3, in
from cStringIO import StringIO
ImportError: No module named 'cStringIO'
Throws an import error when i'm importing Images from flask images. Running python3.4.0 Flask 0.10.1
Use the imgresizer on a valid image. EG:
http://localhost:5000/imgsizer/test.jpg?h=480&m=crop&v=Yy8dVw&w=640&s=xxxxxx
The URL returns a 500 error.
Exception is:
2022-09-24 17:19:29,310 ERROR werkzeug Thread-310 : Error on request:
Traceback (most recent call last):
File ".\.env\lib\site-packages\werkzeug\serving.py", line 335, in run_wsgi
execute(self.server.app)
File ".\.env\lib\site-packages\werkzeug\serving.py", line 322, in execute
application_iter = app(environ, start_response)
File ".\collectives\.env\lib\site-packages\flask\app.py", line 2548, in __call__
return self.wsgi_app(environ, start_response)
File ".\collectives\__init__.py", line 40, in __call__
return self.app(environ, start_response)
File ".\.env\lib\site-packages\flask\app.py", line 2528, in wsgi_app
response = self.handle_exception(e)
File ".\.env\lib\site-packages\flask\app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File ".\.env\lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File ".\.env\lib\site-packages\flask\app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File ".\.env\lib\site-packages\flask\app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File ".\.env\lib\site-packages\flask_images\core.py", line 432, in handle_request
return send_file(cache_path, mimetype=mimetype, cache_timeout=cache_timeout)
TypeError: send_file() got an unexpected keyword argument 'cache_timeout' datefmt=
Image should be downloadable without a 500 error.
Flask has updated their send_file
function by deprecating some key word argument. See https://github.com/pallets/flask/blob/73b9bacbf7e7440e5a8a65e61fecfe3d0ce75579/CHANGES.rst#version-220 . Code update from flask_image is required.
These would be very welcome additions.
See: http://pmt.sourceforge.net/pngcrush/ and http://pngquant.org/
I believe that both of them have relatively small sources, and so could be compiled together into a C (or Cython) extension module (which should really be another project anyways).
Running my server from localhost and trying to link to an external file produces a ValueError. Is this type of usage allowed?
src="{{resized_img_src('www.example.com/pics/mypicture.jpg'
it throws an error:
raise ValueError('path is not normalized')
Faced the problem that the link to the image contains quotes:
/imgsizer/image.jpg?v=WzdUWw&w=480&s=b'PKgfqQAtQuvQseN6-gErB3tRjtM'
The whole problem in the s
parameter, looks like the bytes are converted incorrectly into a string.
Python 3.7
Flask-Images 3.0.1
Linux Mint 19
Hi @mikeboers thanks for this awesome extension
I have an issue to use flask-images with Flask-Apscheduler, I have a cron job to send email which is has images in my email template that needs to be sent along with email, all the app context is working good but the flask-images throws error
File "../email/myemail.html", line 32, in top-level template code <img src="{{ url_for('images.crop', filename='uploads/image.jpg', width=64, height=64, quality=95, _external=True) }}"/> File "../python2.7/site-packages/flask/helpers.py", line 332, in url_for return appctx.app.handle_url_build_error(error, endpoint, values) File "../python2.7/site-packages/flask/app.py", line 1800, in handle_url_build_error rv = handler(error, endpoint, values) File "../python2.7/site-packages/flask_images/core.py", line 124, in build_error_handler return self.build_url(filename, mode=mode, **values) File "../python2.7/site-packages/flask_images/core.py", line 206, in build_url scheme or request.scheme,
RuntimeError: Working outside of request context.
but still doesnt work, any idea?
The important parameter to me is the IMAGES_URL
, but probably override all parameters can be useful in some cases.
Many plugins use something like plugin.init_app(app, url_prefix='/xxx')
, it is really cleaner than a config variable.
Hello @mikeboers,
Can you describe how to install it in readme please?
[:debug] last_modified: datetime.datetime(2015, 11, 10, 23, 20, 1, 80586) [:debug] if_modified_since: datetime.datetime(2015, 11, 10, 23, 20, 1)
That makes last_modified bigger than if_modified_since because of the microseconds
Impact: no 304 (Not modified) is sent, but the picture itself.
My ugly patch was:
mtime = datetime.datetime.utcfromtimestamp(raw_mtime) - datetime.timedelta(seconds=1)
That works for me, but doesn't solve the real problem. Root cause is unknown for me, but the header will never have parts of seconds set.
Hi, can you do this with send_from_directory?
Hi, I have issue regarding the RGBA image, seems Pillow bug, below the errors
File "flask_images/core.py", line 395, in handle_request
image.save(cache_file, format, quality=quality)
File "PIL/Image.py", line 1930, in save
save_handler(self, fp, filename)
File "PIL/JpegImagePlugin.py", line 607, in _save
raise IOError("cannot write mode %s as JPEG" % im.mode)
Traceback (most recent call last):
File "app.py", line 10, in
from config import app,db,allowed_file
File "D:\display\config.py", line 5, in
from flask.ext.images import resized_img_src
File "C:\Users\JOHN\Envs\display\lib\site-packages\flask\exthook.py", line 96, in load_module
reraise(exc_type, exc_value, tb.tb_next)
File "C:\Users\JOHN\Envs\display\lib\site-packages\flask_compat.py", line 32, in reraise
raise value.with_traceback(tb)
File "C:\Users\JOHN\Envs\display\lib\site-packages\flask_images__init__.py", line 1, in
from .core import Images, resized_img_src, resized_img_size, resized_img_attrs, resized_img_tag
File "C:\Users\JOHN\Envs\display\lib\site-packages\flask_images\core.py", line 3, in
from cStringIO import StringIO
ImportError: No module named 'cStringIO'
My jpeg image is loaded with image.mode == 'L'
. The resize
function override this mode to RGBA
and it breaks Pillow.
https://github.com/mikeboers/Flask-Images/blob/master/flask_images/core.py#L225
I just commented this mode
override and it worked. I don't know why this mode change is there.
More of a feature request than an issue:
If an uploaded image is 200x400px, and in crop mode the desired output is 400px by 400px, would it be possible to allow the outputted image to be a zoomed/enlarged cropped image that is 400x400px and zoomed on the centre of the image? Right now, the output will never be larger than the original (and would output an image of the original 200x400 size in the above example).
The _external
fix is really important to me now and it is not released yet.
Can you push a new release to PyPI?
IMAGES_PATH
seems to only work as a list, can someone at least put this in the docs.
IMAGES_NAME
, I can't for the life of me figure out what this does
Also it would be nice to have the from flask.ext.images import resized_img_src
or url_for
somewhere in the docs.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.