将图像PIL对象从视图传递到其他视图django

时间:2018-02-23 08:26:07

标签: python django python-imaging-library

如何将PIL Image对象从一个视图def传递到其他视图def?使用reverse()函数是可行的。我想在不保存的情况下在imageSizeConverter视图上显示更改的图像。我的代码是

def imageSizeConverter(request):
        if request.method == 'POST':
            item = request.FILES.get('imgInp')

            width = int(request.POST.get('width'))
            height = int(request.POST.get('height'))

            proportion = request.POST.get('proportion')

            root = tk.Tk()
            root.withdraw()
            file_path = filedialog.askdirectory()
            name = request.POST.get('fname')

            print(file_path)
            img = Image.open(item)

            if(proportion == 'on'):
                img.thumbnail((width, height))
            else:
                img.resize((width, height))

            resultFileName, file_extension = os.path.splitext(name)

            if not file_extension:
                filename, file_extension = os.path.splitext(item.name)
            nazwa = file_path + "/" + resultFileName + file_extension
            img.save(nazwa)

            return render(request, "app/imageSizeConverter.html", 
                          {
                              'title':'Zmiana rozmiaru',
                              'year':datetime.now().year,
                              'image': reverse('show_image')
                          })  

def show_image(request):
    response = HttpResponse(content_type="image/png")
    img.save(response, "PNG")
    return response

修改

这是我的问题的解决方案:

output = BytesIO()
img.save(output, format='JPEG')
im_data = output.getvalue()
data_url = 'data:image/jpg;base64,' + base64.b64encode(im_data).decode()

return render(request, "app/imageSizeConverter.html", 
              {
                   'title':'Zmiana rozmiaru',
                   'year':datetime.now().year,
                   'image': data_url
              })       

并在模板上使用:

<img src="{{ image }}" alt=""/>

0 个答案:

没有答案