How to insert image blob in openpyxl

Question:

In my web app I’am using openpyxl to create or modify excels and there’s a part of my web that i need to insert image with a blob or base64 ?, I dont see anything related in how to inserting image in openpyxl except in a method where i need to pass a relative or absolute path of the image. i don’t want to save the image first to my project directory before using it for the excel.

@route(data_mgt, rule='/elevation-values-calculation/download-error-ratio', methods=['POST'])
def download_error_ratio():

    payl = payload()

    survey_id = payl.get('survey_id', {})
    project_id = payl.get('project_id', {})

    image = request.files['image'] #return blob

    image_string = base64.b64encode(image.read()) #return base64 string

    base64_string = "data:{content_type};base64,{img_string}".format(
        content_type=image.content_type, 
        img_string=image_string.decode()
    )

    wb = openpyxl.Workbook()
    ws = wb.worksheets[0]
    img = openpyxl.drawing.image.Image(base64_string) #error need to pass absolute or realte image path
    img.anchor = 'A1'
    ws.add_image(image)

Answers:

When you get a file from request.files it is wrapped in a FileStorage, which can be used in the openpyxl.drawing.image.Image directly as it accepts either a filename or an open file.

The following minimal app works to receive images and put them at "A1".

from flask import Flask, request
from openpyxl import Workbook
from openpyxl.drawing.image import Image

app = Flask(__name__)


@app.route("/add_image", methods=["POST"])
def handle_add_image():

    wb = Workbook()
    ws = wb.active

    img = Image(request.files["image"])
    ws.add_image(img, "A1")

    wb.save("/tmp/74981726.xlsx")
    return b"OK"

Tested with cURL:

curl -i -X POST -F image=@Downloads/5x1aqu4dtuny.png http://127.0.0.1:5000/add_image
Answered By: ljmc
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.