How do I resize an image to be rendered in template without affecting original image?

Viewed 33

I tried resizing the image in my views.py using PIL, but it resizes the original image too which I don't want. I just to want resize a copy to be passed unto templates but can't seem to figure that out. Is there something obvious I'm missing?

Views.py

def home(request):
    if request.method == "POST":
        pass
    vendors = Vendor.objects.all()
    size = (360, 200)
    for vendor in vendors:
        try:
            image = Image.open(vendor.image)
        except:
            continue
        image.thumbnail(size)
        image.save(vendor.image.path)

    context = {'vendors': vendors}
    return render(request, 'home.html', context)

Models.py

class Vendor(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, unique=True) 
    image = models.ImageField(null=True, blank=True)


    def __str__(self):
        return self.name

    @property
    def imageURL(self):
        try:
            url = self.image.url
        except:
            url = ''
        return url
1 Answers

I don't use models, views or djangos but the thumbnail() method does indeed alter the image you call it on in-place.

If you wish to preserve the original, you need to work on a copy.

th = original.copy()
th.thumbnail(size)
Related