2

How do I pass a PIL Image object from one view def to another view def? It is possible to use a reverse() function. I would like to display the changed image on the imageSizeConverter view without saving. My code is

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

Edit

This is the solution to my problem:

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
      })  

And use on the template:

<img src="{{ image }}" alt=""/>
Usman Maqbool
  • 3,351
  • 10
  • 31
  • 48
panopticon
  • 21
  • 3

0 Answers0