surya raj
surya raj

Reputation: 195

How to convert a HttpResponse to an image in Django? just like screenshot

I want a png file and some dynamic values as response for a view, and which is working fine. Now I need to convert this httpresponse to an image to upload to the s3 bucket. Just like taking a screenshot of the HttpResponse. Is there any package ? I tried imgkit and html2image, it didnt work well.

def home(request):
    im_io = io.BytesIO()
    im = Image.open(r'test.png')
    im.save(im_io, 'png', quality=70)
    im_io.seek(0)
    im_io_png = base64.b64encode(im_io.getvalue())
    context = im_io_png.decode('UTF-8')
    img_tag = mark_safe(f"<img src='data:image/png;base64, {context}'/>")
    return render(request, 'api/home.html',{'img_tag': img_tag})

Upvotes: 0

Views: 255

Answers (1)

Patryk Szczepański
Patryk Szczepański

Reputation: 784

I don't get what you wanna exactly todo... Do you wan't to put your image into the template, or return HttpResponse with file?

Basically your code should work fine I think, I used similar base64 converter in my project:

def get_file_data(file_path):
    """Get data of a file."""
    with open(file_path, 'rb') as f:
        data = f.read()
        f.close()
        return data


@register.simple_tag
def to_base64(path):
    """Convert to base64."""
    file_path = find(path)
    ext = file_path.split('.')[-1]
    file_str = base64.b64encode(get_file_data(file_path)).decode()
    return f'data:image/{ext};base64,{file_str}'

You can try to rewrite your logic to match my code.

But, if you need to return FileResponse, you can do this way:

return FileResponse(
    ContentFile(
        file_buffer.getvalue(),
        'YourImageName.extension'
    ),
    as_attachment=True,
)

Check it out.

Upvotes: 1

Related Questions