1

I was wondering if it's possible to save an generated image from my template to the MEDIA_URL? My image is generated in base64, I would like to give it a name and save it as png or jpeg to the MEDIA_URL

<img id="canvasImg" style="display:none;" src="data:image/png;base64,iVB...">

My image is generated using the html2canvas script. I then use this function to transform the canvas into an image:

function canvas2img(){
      html2canvas(document.getElementById("bg"), {
        onrendered: function(canvas) {      
          canvas.setAttribute("id", "canvas");
          var dataURL = canvas.toDataURL('image/png', 1.0);
          document.getElementById('canvasImg').src = dataURL;  
        }
      })
   };

Thank you!

l4c
  • 25
  • 5

1 Answers1

2

I won't post the full code here just some guidance, everything from StackOverflow:

First you need to send your base64 image to django using AJAX: https://stackoverflow.com/a/13198699/263989

Then get the base64 in an AJAX function:

from django.http import HttpResponse
def get_bas64(request):
    if request.is_ajax():
        # process the image
        return HttpResponse('')

To convert the base64 string to an image using PIL https://stackoverflow.com/a/19911883/263989

Community
  • 1
  • 1
fasouto
  • 4,386
  • 3
  • 30
  • 66
  • Thank you very much for your reply but I having trouble sending the base64 image to django. Can you plase explain me how to do it? – l4c May 09 '14 at 01:34
  • I'm getting `The view userdata.views.get_base64 didn't return an HttpResponse object.` – l4c May 09 '14 at 02:10
  • Yeah, you need to return an HTTPResponse, I edited the answer – fasouto May 09 '14 at 02:16
  • Ok but I can't seem to send an AJAX request to my view, it always returns "Not Ajax" `@login_required @csrf_exempt def get_base64(request): if request.is_ajax(): pic = cStringIO.StringIO() image_string = cStringIO.StringIO(base64.b64decode(request.POST['file'])) image = Image.open(image_string) image.save(pic, image.format, quality = 100) pic.seek(0) return HttpResponse(pic, content_type='image/jpeg') else: return HttpResponse("Not AJAX")` – l4c May 09 '14 at 02:29
  • I have created images upload like as facebook and amazon! Thanks for solutions! – miltonbhowmick Aug 01 '20 at 09:34