当我在Django的视图中上传文件时,我试图调整大小(创建有效的缩略图)并重命名文件。我看到了库PIL并且正在使用它,但没有结果。
views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.core.files.storage import FileSystemStorage
from django.urls import reverse
from PIL import Image
@login_required
def zoom(request):
uploaded_url = {}
if request.method == 'POST' and request.FILES.getlist('document', False):
myfiles = request.FILES.getlist('document')
for myfile in myfiles:
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
uploaded_url[filename] = uploaded_file_url
imagen = ((Image.open(myfile)).resize((191,176))).save("thumb.png")
return render(request, "visores/acercamiento.html", {
'uploaded_url' : uploaded_url,
})
acercamiento.html
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
<h4>Búsqueda general</h4>
<input type="file" name="document" accept="image/*" id="b">
<button type="submit" id="subir">Subir imagen</button>
</form>
{% if uploaded_url %}
{% for name, url in uploaded_url.items %}
{% load static %}
<div id="bai">
<a class="magnifier-thumb-wrapper demo" href="{{ url }}">
<img id="thumb2" src='http://127.0.0.1:8000/media/thumb.png'>
</a>
</div>
{% endfor %}
{% endif %}
预期结果: /media/P1565.png /media/thumb.png
实际结果: /media/P1565.png
答案 0 :(得分:2)
那是因为您没有将新保存的缩略图的URL返回到模板中。
filename = fs.save(myfile.name, myfile) # you're saving "P1565.png";
uploaded_file_url = fs.url(filename) # you're getting the URL for "P1565.png";
uploaded_url[filename] = uploaded_file_url # the URL value is "/media/P1565.png";
因此,在调整大小并保存后,应将upload_url值设置为thumb.png URL。
thumb_url = os.path.join(os.path.dirname(uploaded_file_url), 'thumb.png') # specify your thumbnail URL;
imagen = ((Image.open(myfile)).resize((191,176))).save('thumb.png') # re-size and save your thumbnail to the corresponding path;
uploaded_url[filename] = thumb_url # assign the new URL as the new value;
答案 1 :(得分:1)
我解决了!感谢@Viktor Petrov,这是将代码保存在地毯“媒体”中的部分代码:
thumb_url = os.path.join(os.path.dirname(uploaded_file_url), 'thumb.png') # specify your thumbnail URL;
imagen = (Image.open(myfile)).resize((191,176),Image.ANTIALIAS).save(os.path.join(MEDIA_ROOT,'thumb.png')) # re-size and save your thumbnail to the corresponding path;
uploaded_url['thumb.png'] = thumb_url