简体   繁体   English

在上传之前在Django中调整图片大小?

[英]Resize an image in Django before upload?

How can I resize an image before uploading it in Django? 在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. 我有一个屏幕,用户可以在其中上传图像,但是在他们上传图像之前,我想将其缩放到500,500。

In PIL I can easily do this locally via: 在PIL中,我可以通过以下方式轻松地在本地执行此操作:

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? 我将如何在Django视图中执行此操作而不必先上传图像?

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. 因此,使用“浏览器在上传前调整图片大小”一词的Google搜索将为您提供帮助。 You'll have to edit the image with javascript and then submit it to your server. 您必须使用javascript编辑图像,然后将其提交到服务器。

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. 但是,如果您要处理已上传的图像,则需要枕头 (您提到的PIL的前叉)。 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 . 提交表单后(我假设您是通过表单获取图像的),该文件将位于您的服务器上,并且在viewrequest.FILES中可以找到对该文件的引用。 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- . 您可以对映像进行任何操作,然后将其保存到磁盘上的原始位置,或者根据需要保存到其他位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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