简体   繁体   中英

Resize an image in Django before upload?

How can I resize an image before uploading it in Django?

I have a screen where a user can upload an image, but before they upload it, I would like to scale it to 500,500.

In PIL I can easily do this locally via:

from PIL import Image

img = Image.open("/Users/Admin/Desktop/example.jpg")
img = img.resize((750,500),Image.ANTIALIAS)
img.save()

How would I go about doing this in a Django view without having to upload the image first?

First of all, if you want to do anything with that file on your server, the file needs to be uploaded. That's the only way.

If what you want to do is really manipulate the image before uploading it, you need to do that on the browser, client-side. So, a Google search with term "browser resize image before upload" will help you. You'll have to edit the image with javascript and then submit it to your server.

But, if you want to manipulate an image which is already uploaded, pillow (maintained fork of the PIL you mentioned) is the tool you need. Once the form is submitted (i assumed you are getting the image via form), the file will be on your server and reference to that file will be available in your request.FILES at the view . You can do whatever you want with that image, and then save it -to the original location on disk, or a different one, according to your requirements- .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM