GithubHelp home page GithubHelp logo

mikeboers / flask-images Goto Github PK

View Code? Open in Web Editor NEW
82.0 82.0 44.0 227 KB

On-demand resizing of images for Flask applications.

Home Page: https://mikeboers.github.io/Flask-Images/

License: BSD 3-Clause "New" or "Revised" License

Python 99.89% Procfile 0.11%

flask-images's People

Contributors

geneguido avatar iurisilvio avatar macrojames avatar mikeboers avatar ovionlogis avatar riverfount avatar wzuo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flask-images's Issues

Such a poor plugin

There are so many bugs still left when using with python3,such as urllib bugs ,StringIO

Allow files based on name

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?

Pass a image generator URL to u parameter

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:

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

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.

AttributeError: 'Flask' object has no attribute 'add_template_global'

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'

Animated GIF loses transparency and animation

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:

http://imgur.com/2D7aWd3.gif

Serving images with nginx?

How could I serve cached images as static files with nginx (or another webserver) after they was generated? Is it possible with Flask-Images ?

How to use 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&amp;w=50&amp;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!

Delete Cached File

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

Flask-Images not working on Python 3.5

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.

Use url_for instead of a custom function

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.

Predict dimensions for img tag

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.

Exif orientation

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?

Compatibility with itsdangerous 2.0.0

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'

Generated image is bigger than original

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

How to use Flask_Images with a document api endpoint?

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!

cannot use 'resized_img_tag' in python3

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'

fail to load url

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?

Add plugin to Flask Extensions page

  • An approved Flask extension requires a maintainer. In the event an extension author would like to move beyond the project, the project should find a new maintainer including full source hosting transition and PyPI access. If no maintainer is available, give access to the Flask core team.
  • An approved Flask extension must provide exactly one package or module named flask_extensionname. They might also reside inside a flaskext namespace packages though this is discouraged now.
  • It must ship a testing suite that can either be invoked with make test or python setup.py test. For test suites invoked with make test the extension has to ensure that all dependencies for the test are installed automatically. If tests are invoked with python setup.py test, test dependencies can be specified in the setup.py file. The test suite also has to be part of the distribution.
  • APIs of approved extensions will be checked for the following characteristics:
    an approved extension has to support multiple applications running in the same Python process.
    it must be possible to use the factory pattern for creating applications.
  • The license must be BSD/MIT/WTFPL licensed.
  • The naming scheme for official extensions is Flask-ExtensionName or ExtensionName-Flask.
  • Approved extensions must define all their dependencies in the setup.py file unless a dependency cannot be met because it is not available on PyPI.
  • The extension must have documentation that uses one of the two Flask themes for Sphinx documentation.
  • The zip_safe flag in the setup script must be set to False, even if the extension would be safe for zipping.
  • An extension currently has to support Python 2.6 as well as Python 2.7

Support Python 3

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

Flask v2.2.0 changes some keyword argument

Initial conditions:

  • Flask-Images==3.0.2
  • Flask==2.2.2

Reproduction step

Use the imgresizer on a valid image. EG:

http://localhost:5000/imgsizer/test.jpg?h=480&m=crop&v=Yy8dVw&w=640&s=xxxxxx

Observed Behavior

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=

Expected behavior:

Image should be downloadable without a 500 error.

First analysis

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.

URL normalization on Windows

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

The generated link contains quotes

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

Not working on Cron job

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?

Configure with kwargs in app initialization

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.

Setup

Hello @mikeboers,

Can you describe how to install it in readme please?

if_modified_since is not respected

[: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.

IOError: cannot write mode RGBA as JPEG

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)

Python 3.5 dont work!

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'

Crop Resize

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

Release!

The _external fix is really important to me now and it is not released yet.

Can you push a new release to PyPI?

Improve docs re: configuration and examples

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.