1

I want to have method that will give me resized image, if i call this method on object, how can i do this with Pillow?

my model:

class Item(models.Model):
    title = models.CharField(max_length=255, null=True)
    img = models.ImageField()

    def __str__(self):
        return self.owner.first_name

    def get_image(self):
        image = Image.open(self.img)
        resized_image = image.resize((128, 128))

        return resized_image

This one always gives me something like that

<PIL.Image.Image image mode=RGB size=128x128 at 0x7F001CF92D30>
irakli
  • 62
  • 8
  • This question is very similar to https://stackoverflow.com/questions/30434323/django-resize-image-before-upload#30435175 – Loki Mar 14 '18 at 18:56
  • i don't want to save resized image. Is it possible to get already saved image without creating new resized instance? – irakli Mar 14 '18 at 18:59

2 Answers2

0

If you only want to display the image resized (without resizing the actual image itself) you can do it in directly in the html/css:

for example:

in the HTML

<div class="container">
<img src="something.png" />
</div>

<div class="container">
<img src="something2.png" />
</div>

In the Css:

.container {
    width: 200px;
    height: 120px;
}

/* resize images */
.container img {
    width: 100%;
    height: auto;
}

I hope this helps.

Loki
  • 70
  • 1
  • 11
0

Source https://www.youtube.com/watch?v=5t6kgAEMIB8

I found this recently it may be helpful:

In your forms.py:

from PIL import Image
from django import forms
from django.core.files import FILE
from .models import YourModel

class YourModelForm(forms.ModelForm):

    x = forms.FloatField(widget=forms.HiddenInput())
    y = forms.FloatField(widget=forms.HiddenInput())
    width = forms.FloatField(widget=forms.HiddenInput())
    height = forms.FloatField(widget=forms.HiddenInput())

        class Meta:
            model = YourModel
            fields = '__all__'
            exclude = ['user', 'date_joined','Credits_earned','skills']

    def save(self):
        photo = super(YourModelForm,self).save()

        x = self.cleaned_data.get('x')
        y = self.cleaned_data.get('y')
        w = self.cleaned_data.get('width')
        h = self.cleaned_data.get('height')

        image = Image.open(photo.file)
        cropped_image = image.crop((x,y,w+x,w+y))
        resized_image = cropped_image.resize((1200,600), Image.ANTIALIAS)
        resized_image.save(photo.file.path)

        return photo

And here's the JS to handle it in your template:

<script>
$(function () {

    // SCRIPT TO OPEN THE MODAL WITH THE PREVIEW
    $("id_file").change(function () {
        if (this.files && this.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $("#image").attr("src", e.target.result);
                $("#modalCrop").modal("show");
            }
            reader.readAsDatarURL(this.files[0]);
        }
    });

    // SCRIPTS TO HANDLE THE CROPPER BOX
    var $image = $("image");
    var cropBoxData;
    var canvasData;
    $("#modalCrop").on("shown.bs.modal", function () {
        $image.cropper({
            viewMode: 3,
            movable: false,
            zoomable: false,
            scalable: false,

            ready: function () {
                $image.cropper("setCanvasData", canvasData);
                $image.cropper("setCropBoxData", cropBoxData);
            }
        });
    }).on("hidden.bs.modal", function () {
        cropBoxData = $image.cropper("getCropBoxData");
        canvasData = $image.cropper("getCanvasData");
        $image.cropper("destroy");
    });

    $(".js-zoom-in").click(function () {
        $image.cropper("zoom", 0.1);
    });

    $(".js-zoom-out").click(function () {
        $image.cropper("zoom", -0.1)
    });

    // SCRIPT TO COLLECT THE DATA AND POST TO THE SERVER
    $(".js-crop-and-upload").click(function () {
        $("#id_x").val(cropData["x"]);
        $("#id_y").val(cropData["y"]);
        $("#id_height").val(cropData["height"]);
        $("#id_width").val(cropData["width"]);
        $("#formUpload").submit;
    });

});

</script>

you can chanage the id manually in the script in order to match your template, or you could use the one in the video () although you will have to pause it and code it. Also if you use Function-Based-Views instead of Class-Based-Views you will have to add the files to the form validation for example:

def YourView(request)
    if request.method == 'POST':
        form = YourModelForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            form.save()
            return redirect('Your_redirect_URL')
    else:
        form = YourModelForm()
    return render(request, 'YourTemplate.html', {'form': form})
Loki
  • 70
  • 1
  • 11
  • Hi! You have several errors in your'e code. For example, the function on reader is readAsDataURL and not readAsDatarURL. But at the end, it does not fix my error that cropper is not a function :( – HolgerT Jan 19 '20 at 18:49