Jinvan
Jinvan

Reputation: 33

How can I get the uploaded image's width and height in django?

How can I get the uploaded image's width and height in django?

Don't use PIL.

Upvotes: 2

Views: 3732

Answers (3)

Eric Andrews
Eric Andrews

Reputation: 956

ImageField will deal with the width and height of the image automatically. You do NOT need to do ANY THING.

  1. Change the project setting

Append these code at the end of the setting.py in project directory

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

and then change the urls.py in the project directory

urlpatterns = [
    path('admin/', admin.site.urls),
    path(...),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  1. Provide two integer fields to store the image's width and height

models.py

class Picture(models.Model):
    image = models.ImageField(upload_to='images/', width_field = 'image_width', height_field='image_height')
    image_width = models.IntegerField(default=0)
    image_height = models.IntegerField(default=0)
  1. Create a Form, DO NOT INCLUDE "image_width" and "image_height", which are supposed to be hidden and filled automatically.

forms.py

class PictureForm(forms.Form)
    image = forms.ImageField()
  1. Validate and process form in view and save the data into database

views.py

def createPicture(request):
    form = PictureForm(request.POST, request.FILES)
    if form.is_valid():
        picture = Picture()
        picture.image = form.cleaned_data['image']
        picture.save()
        return HttpResponseRedirect(reverse('picture-list'))
    else:
        form = PictureForm()
    return render(request, 'template_file', {'form' : form})

Upvotes: 2

Burhan Khalid
Burhan Khalid

Reputation: 174624

Django has ImageField which will do this calculation automatically, but you need PIL installed.

Once you have set it up, you'll get height and width attributes for your images automatically, so you can do this:

class SomeModel(models.Model):
   img = models.ImageField(upload_to='images/')

foo = SomeModel.objects.get(pk=1)
print('The height is {0.height} and the width is {0.width}'.format(foo.img))

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

Delegate to a package specifically for handling images. Such as PIL.

Upvotes: 0

Related Questions