Render image without saving

后端 未结 3 691
梦谈多话
梦谈多话 2021-01-22 20:44

I want to get an image from user, work with it at beckend and render result back to user. Is it possible to do without saving image on disk?

my view:

cla         


        
3条回答
  •  无人及你
    2021-01-22 21:37

    If your form is Model Form .then jus try the below code.

    from django.core.files import File
    from django.core.files.temp import NamedTemporaryFile
    
    class InputImageForm(forms.Form):
        image = forms.ImageField()
        class Meta:
           model = YourModel
    
    
    
    def get_image(request):
        if request.method == 'POST':
            form = InputImageForm(request.POST, request.FILES)
            if form.is_valid():
                image = request.FILES['image']
                save_image_from_url(form,image)
    
            else:
               form = InputImageForm()
        else:
            raise Http404
    
    
    
    def save_image_from_url(model, img):
        r = request.FILES['image']
    
        img_temp = NamedTemporaryFile(delete=True)
        img_temp.write(r.content)
        img_temp.flush()
    
        i = model.image.save("image.jpg", File(img_temp), save=True)
        return HttpResponse(i.read(), mimetype="YOUR MIME TYPE")
    

提交回复
热议问题