un1t / django-resized Goto Github PK
View Code? Open in Web Editor NEWResizes image original to specified size. Compatible with sorl-thumbnail
Resizes image original to specified size. Compatible with sorl-thumbnail
So I have this original Image from pexels:
But when I upload it to our Django model which is defined as:
picture640 = ResizedImageField(upload_to="influencer_profile640", null=True, blank=True, quality=80, size=[640, 640], crop=['middle', 'center'])
the image on the server then looks like
So I tired to reproduce this error locally. I achieved it by setting quality=0, but I haven't set the quality=0 in the model.
from PIL import Image, ImageOps
def square_image(img, size):
img_width, img_height = img.size
new_size = min(img_width, img_height)
img = img.crop(((img_width - new_size) // 2, (img_height - new_size) // 2, (img_width + new_size) // 2, (img_height + new_size) // 2))
new_image = img.resize((size, size), Image.ANTIALIAS)
return new_image
img = Image.open('original.jpg')
profile_image = square_image(img, 640)
profile_image.save('looks_how_it_is_supposed_to_look.jpg', optimize=True, quality=80)
profile_image.save('looks_the_same_as_on_the_server.jpg', optimize=True, quality=0)
This is the "looks_how_it_is_supposed_to_look.jpg" image
So my question is: "Why does it not use the attribute quality=80? And the quality of the image on the server is so bad?"
Thanks for this app, it really fills a gap that Django is missing! One thing that would be beneficial is the ability to tell the field to always save in JPEG format. Images take up way more space if users upload images in PNG format, and pillow makes the conversion super trivial.
If so, can I add that to the .md file?
I receive the error "OSError: cannot write mode CMYK as PNG" everytime I try to save a image with CMYK mode.
(I use "PNG" as the "DJANGORESIZED_DEFAULT_FORCE_FORMAT")
Digging into the source code I wonder why would only JPEG and JPG be the ones that can benefit from automatic conversion to RGB when it would be advantageous to PNG as well.
If I misunderstood something, please, let me know!
Thanks for the lib.
If you are formatting as .webp and you don't include quality
you get an invalid configuration error.
1 - Add a new field to a model such as:
img = ResizedImageField(force_format="WEBP", upload_to="post_imgs/")
2 - Try to upload a png or a jpeg
ValueError: invalid configuration
Provide the quality
property to the field
img = ResizedImageField(force_format="WEBP", quality=75, upload_to="post_imgs/")
Everything works as expected
Python 3.8.10
django-resized==1.0.1
Pillow==9.2.0
If a PNG image with a transparency layer is uploaded the error cannot write mode RGBA as JPEG
In this issue (python-pillow/Pillow#2609) the following code fix is suggested:
fill_color = '' # your background
image = Image.open(file_path)
if image.mode in ('RGBA', 'LA'):
background = Image.new(image.mode[:-1], image.size, fill_color)
background.paste(image, image.split()[-1])
image = background
im.save(hidpi_path, file_type, quality=95)
There are some JPEG images taken with iPhone that after I upload them in the Django admin they got rotated after resizing. I force JPEG format. Maybe because the rotation metadata isn't saved?
My model
image = ResizedImageField('Головне фото', size=[1024, 1024], upload_to='images')
My settings
DJANGORESIZED_DEFAULT_SIZE = [1920, 1080]
DJANGORESIZED_DEFAULT_QUALITY = 75
DJANGORESIZED_DEFAULT_KEEP_META = True
DJANGORESIZED_DEFAULT_FORCE_FORMAT = 'JPEG'
DJANGORESIZED_DEFAULT_FORMAT_EXTENSIONS = {'JPEG': ".jpg"}
DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = True
The photo for example I have attached.
After upload the photo got rotated(90deg). Here is what happened to it.
Hello. This release introduced a check on field.force_format but it makes the code throw an exception when force_format is not defined in your field.
Hi
Is there any issues with this version and Django resized? Following the installation guide it seems that
from django_resized import ResizedImageField
is accepted however ResizedImageField is not as such recognised, but not rejected at all. Using ResizedImageField in the model does not bring up any errors but the images are not resized nor saved to be viewed.
Hey guys,
I'm a huge fan of your work - very much appreciated. However, I have noticed in the past, that the conversion from a transparent PNG to a JPG can change the picture in unwanted ways because transparent pixels can have unpredictable colours. Please also have a look at this comment which suggests a solution using Pillow:
python-pillow/Pillow#2609 (comment)
Is there any chance that this will be fixed?
Hi,
i'm using the PIL fork pillow (as it's easy to install in a virtualenv), and got a problem with your work:
import Image doesn't work with pillow (design choice), and so require a from PIL import Image, it's possible to change the import such that we no longer have to modify the core files?
Cheers and thanks for your work
Trying out image resizing. How do I keep the ratio intact? I just want to resize width and height resized automatically. Any support on that? Kept searching but in vain. For example like below, just width.
size=[990],
i suggest to add this attributes:
picture = ResizedImageField(max_width=640, max_height=640)
i think its better than quality
Hello guys!
Would be desirable a changeset that resizes gif ?
Hey there,
is there a way to rename the image?
When the images are uploaded by my endusers and stored all in the same folder, I would need to change the name of the image since I can't guarantee that there will be no collisions in the naming. I would like to set the name to an UUID.
I tried to set name=uuid.uuid4
but that did not work at all.
How to save photo form url like from Facebook?
The South compatibility changes from #3 haven't been pushed to pypi yet.
Hi. By default django-resized has a JPEG quality of 0:
DEFAULT_QUALITY = getattr(settings, 'DJANGORESIZED_DEFAULT_QUALITY', 0)
(from django_resized/forms.py
).
This worked fine with old Pillow releases, because they treated 0 as 'default' quality.
But Pillow 7.1.0 (released 2020-04-01) actually implements JPEG quality 0: python-pillow/Pillow#4439
As you can imagine, this results in horribly poor quality.
After updating to the version 0.3, I cannot use South Migrations. Since the arguments to ResizedImageField
changed from max_width
and max_height
to size
, I keep getting this error while migrating.
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/jaskaran/Desktop/coding/edmhunters/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/Users/jaskaran/Desktop/coding/edmhunters/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/jaskaran/Desktop/coding/edmhunters/env/lib/python2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Users/jaskaran/Desktop/coding/edmhunters/env/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute
output = self.handle(*args, **options)
File "/Users/jaskaran/Desktop/coding/edmhunters/env/lib/python2.7/site-packages/south/management/commands/schemamigration.py", line 111, in handle
old_orm = last_migration.orm(),
File "/Users/jaskaran/Desktop/coding/edmhunters/env/lib/python2.7/site-packages/south/utils/__init__.py", line 62, in method
value = function(self)
File "/Users/jaskaran/Desktop/coding/edmhunters/env/lib/python2.7/site-packages/south/migration/base.py", line 432, in orm
return FakeORM(self.migration_class(), self.app_label())
File "/Users/jaskaran/Desktop/coding/edmhunters/env/lib/python2.7/site-packages/south/orm.py", line 48, in FakeORM
_orm_cache[args] = _FakeORM(*args)
File "/Users/jaskaran/Desktop/coding/edmhunters/env/lib/python2.7/site-packages/south/orm.py", line 127, in __init__
self.models[name] = self.make_model(app_label, model_name, data)
File "/Users/jaskaran/Desktop/coding/edmhunters/env/lib/python2.7/site-packages/south/orm.py", line 324, in make_model
field = self.eval_in_context(code, app, extra_imports)
File "/Users/jaskaran/Desktop/coding/edmhunters/env/lib/python2.7/site-packages/south/orm.py", line 242, in eval_in_context
return eval(code, globals(), fake_locals)
File "<string>", line 1, in <module>
File "/Users/jaskaran/Desktop/coding/edmhunters/env/lib/python2.7/site-packages/django_resized/forms.py", line 73, in __init__
super(ResizedImageField, self).__init__(verbose_name, name, **kwargs)
File "/Users/jaskaran/Desktop/coding/edmhunters/env/lib/python2.7/site-packages/django/db/models/fields/files.py", line 329, in __init__
super(ImageField, self).__init__(verbose_name, name, **kwargs)
File "/Users/jaskaran/Desktop/coding/edmhunters/env/lib/python2.7/site-packages/django/db/models/fields/files.py", line 230, in __init__
super(FileField, self).__init__(verbose_name, name, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'max_width'
Hello!
I just noticed there's a missing 'b' on use_thumnail_aspect_ratio
Hi
If set force_format='JPEG' and upload GIF it appears the error:
OSError: cannot write mode P as JPEG
forms.py line 88. Before thumb.save(), need Image.convert('RGB').
I am trying to run the following example provided in the README, where crop
is used and one of the dimensions is None
:
image3 = ResizedImageField(size=[100, None], crop=['middle', 'center'], upload_to='whatever')
Trying to do so, results in the following error:
File "/usr/local/lib/python3.9/site-packages/django_resized/forms.py", line 87, in save
thumb = ImageOps.fit(
File "/usr/local/lib/python3.9/site-packages/PIL/ImageOps.py", line 472, in fit
output_ratio = size[0] / size[1]
TypeError: unsupported operand type(s) for /: 'int' and 'NoneType'
It seems that ImageOps.fit()
require both dimensions.
Python 3.9
django-resized 1.0.1
Pillow 9.1.1
i want image to be 48/48 but the size sometimes 40/50,60/40 like.
Hi @Gagaro , I was wondering if there is a way for the filename extension/format to be left the way the image was uploaded.
If a PNG image is uploaded I would like the filename to remain "...png", same for jpeg or jpg. I thought the setting DJANGORESIZED_DEFAULT_FORCE_FORMAT = None
would take care of this, but None
always forces all images to be saved in JPEG format.
Images aren't resizing properly when only using size
parameter and specifying both height and width. Resizing a 400x200 image with size=[200,200]
returns an image of size 200x100 - aspect ratio is maintained here.
I think this may be due to Image.thumbnail
being used instead of Image.resize
when resizing the image when both height and width are provided. Image.thumbnail
preserves aspect ratio, whereas Image.resize
does not.
Please accept my apologies if anything is unclear or if this was the wrong way to bring this up, I'm new to this but am trying to learn :)
How can I pass an image/image path such that if the user does not upload an image, the default image is used? Something similar to
Imagefield(default='path/to/default.png', upload_to='path/to/upload')
I've uploaded to media and my media settings are done. But i cannot access image.url in my templates like regular ImageField model.
Would you take a look at this patch for forms.py. I think copying the data into a new image is the safest way to strip metadata but I don't know if it's the nicest way to implement it.
< def save(self, name, content, save=True, meta_data=False):
---
> def save(self, name, content, save=True):
29,35d28
<
< if meta_data is False:
< nometa = Image.new(img.mode, img.size)
< nometa.format = img.format
< nometa.putdata(img.getdata())
< img = nometa
< ```
Hi @un1t
Are you still willing to maintain this project? There are two interesting PR in waiting and I'd also like to add travis and up to the last Django version testing.
I'm going to fork in order to do this but I can't release on pypi, could you add me as maintainer over there?
Thanks.
Hello, I wanted to know if it has support for Django> 2.x? If this is not the case, I can help to make it happen.
Hi,
can you please upload the master to pypi?
Thanks,
Seb
Since pillow doesn't support HEIF/HEIC by default, i was wondering if there's a way to add support for HEIF/HEIC image format to django-resized?
With a regular image field, you can do this:
image = models.ImageField(upload_to='profile_pic', default='default.jpg')
It doesn't look like you can do this with django-resized.
There is a default parameter that allows me to set a default file.
Python 3.8.10
django-resized==1.0.1
Is it possible to achieve a higher Image quality? I am currently doing:
class MyModel(models.Model):
...
image = ResizedImageField(quality=100, max_width=500, max_height=300, upload_to='whatever')
but there is still a reduction in image quality. Any suggestions?
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.