Saving Image In A Temporary File In Django
I am very new in python and django.I have developed a project using django. Here all the images are watermarked.I have watermarked all the images using the following code... from P
Solution 1:
You need to store the watermarked image into a different file. First you need to create another column to store the Watermarked image.
classPhoto(models.Model):
...
watermarked_photo =ImageField()
Then when you save the watermarked image into that column.
from PIL import Image
defimage_watermark(request,image_id):
photo = Photo.objects.get(pk=image_id)
# Only need to watermark when there's no watermarkifnot photo.watermarked_photo.name:
photo.watermarked_photo.name = 'watermarked_' + photo.photo.name
watermark = Image.open('{0}/{1}'.format(settings.MEDIA_ROOT,'wmark.png'))
img = Image.open(photo.photo.file)
img.paste(watermark,(img.size[0]-watermark.size[0],img.size[1]- watermark.size[1]),watermark)
img.save('{0}/{1}'.format(settings.MEDIA_ROOT, photo.watermarked_photo.name), quality=80)
photo.save()
wrapper = FileWrapper(open(photo.watermarked_photo.url, 'rb'))
response = StreamingHttpResponse(wrapper, 'image/jpeg')
response['Content-Disposition'] = 'attachment; filename=photo.jpg'return response
My Django skill is a bit rusty, so this code might not work without some modification. But the idea should be solid.
If you only want to use a temp file, then try this
from PIL import Image
import tempfile
def image_watermark(request,image_id):
photo = Photo.objects.get(pk=image_id)
watermark = Image.open('{0}/{1}'.format(settings.MEDIA_ROOT,'wmark.png'))
img = Image.open(photo.photo.file)
img.paste(watermark,(img.size[0]-watermark.size[0],img.size[1]- watermark.size[1]),watermark)
tmpfile = tempfile.TemporaryFile()
img.save(tmpfile, img.format, quality=80)
tmpfile.seek(0)
wrapper = FileWrapper(tmpfile)
response = StreamingHttpResponse(wrapper, 'image/jpeg')
response['Content-Disposition'] = 'attachment; filename=photo.jpg'
return response
Post a Comment for "Saving Image In A Temporary File In Django"