How to resize just uploaded image?
In VIEW I开发者_运维问答 want to resize uploaded image and save 2 copies of it in model real and changed
Sorl has great thumbnailing capabilities that can also be used in templates ... it will also check to see if an image is already in the filesystem if not it will create the new resized file.
Depends really where your trying to call the image from.
http://thumbnail.sorl.net/docs
def image_thumb(self):
thumb = DjangoThumbnail(self.image_file, (380, 246))
return '<img src="%s" alt="%s" border="0" />' % (thumb.absolute_url, self.alt)
image_thumb.allow_tags = True
def get_thumb_url(self):
thumb = DjangoThumbnail(self.image_file, (380, 246))
return thumb.absolute_url
Also as I mentioned you can call it directly from the template to load any image.
{% load thumbnail %}
{% thumbnail url 100x100 crop,upscale %}
Obviously you will call the load at the top of your file and the thumbnail where ever you wish for one to appear. The great thing about this too is that you can replace url with python objects such as this
{% thumbnail image.get_absolute_url 150x150 crop %}
The size is self explanatory I would hope and the final crop,upscale are functions of sorl-thumbnail that will have various effects on the final image.
There's 1 things to note at beginning here:
- in your model (database) it's better to save the paths to images, not images themselves. Those should be kept in the filesystem and served directly from there, if possible (unless you don't have the access to the filesystem).
So, in your view, you should do the following:
- Save the uploaded file somewhere (unless it's saved alredy, then you have it's path, goto 2),
- Put the original image path to database,
- Resize it,
- Save the resized image to filesystem,
- Save the path to resized image to your database.
About the points 3 and 4, I do this like that:
orig_img = Image.open(self.imageFile)
orig_img_dim = orig_img.size # (orig_img_dim[0], orig_img_dim[1]) is (y, x) size of image
if (orig_img_dim[0] > 600) or (orig_img_dim[1] > 1000): # only resize images too large
orig_img.thumbnail((600, 1000), Image.ANTIALIAS)
orig_img.save(DESTINATION_FILENAME)
Note that I only resize images that are too large (larger then the 'thumbnail' size).
Use sorl - http://thumbnail.sorl.net/docs/
for you task See this
class MyModel(models.Model):
name = models.TextField(max_length=50)
photo = ImageWithThumbnailsField(
upload_to='profiles',
thumbnail={'size': (50, 50)},
extra_thumbnails={
'icon': {'size': (16, 16), 'options': ['crop', 'upscale']},
'large': {'size': (200, 400)},
},
)
This code doing all you want
Look at this http://biohackers.net/wiki/Django1.0/Thumbnail
Django Imagekit allows you to specify multiple image sizes. The resized images are cached, then you can access them and the original image file in your views and templates.
精彩评论