Reputation: 33
How can I get the uploaded image's width and height in django?
Don't use PIL.
Upvotes: 2
Views: 3732
Reputation: 956
ImageField will deal with the width and height of the image automatically. You do NOT need to do ANY THING.
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)
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)
forms.py
class PictureForm(forms.Form)
image = forms.ImageField()
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
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
Reputation: 798686
Delegate to a package specifically for handling images. Such as PIL.
Upvotes: 0