0

I need to read Base64 encoded image (uploaded by user on Dash app), do some operations using opencv (skip this operation for now) and transform it back to Base64, so that it could be displayed in the browser. The problem is that I never manage to see the output image in a browser, I don't get any errors though.

def parse_contents(contents):
    img1 = data_uri_to_cv2_img(contents)
    _, buffer = cv2.imencode('.jpg', img1)
    jpg_as_text = base64.b64encode(buffer.tobytes())
    second_part = str(jpg_as_text).split('/', 1)[-1]
    to_save = contents.split(',')[0]
    one_string = to_save + ',' + '/'+ second_part
    
return html.Div([
       html.Img(src=one_string, style={'height':'10%', 
    'width':'10%'}),
    html.Hr(),
    html.Div('Raw Content'),
    html.Pre(one_string + '...', style={
       'whiteSpace': 'pre-wrap',
       'wordBreak': 'break-all'
    })
])

@app.callback(
    Output('output-image-upload', 'children'),
    Input('store-data', 'data')
)

The input data looks something like this: contents =

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMA..

When I run the code in notebook, I see the output image, however in app, it looks like on picture

Screenshot of html page

toyota Supra
  • 3,181
  • 4
  • 15
  • 19
elenaby
  • 167
  • 2
  • 11

1 Answers1

2

The function cv2.imencode() returns a Numpy array, so you need to convert that to the bytes you would see in a regular JPEG file before you encode it:

_, buffer = cv2.imencode('.jpg', img1)
jpg_as_text = base64.b64encode(buffer.tobytes())
dataURI = 'data:image/jpeg;base64,' + jpg_as_text

return html.Div([ html.Img(src=dataURI, ...)
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • Thank you, however I still get Error: " Incorrect padding" – elenaby Feb 21 '23 at 12:16
  • 1
    Your base64 representation now looks correct. So you need to put the DataURI prefix (`data:image/jpeg;base64,`) back on the front of that `/9j` string and pass that as the img src. – Mark Setchell Feb 21 '23 at 12:32
  • Thank you a ot for your help! It works in my notebook now, however, when I pass it to img src, the image isn't shown in web browser still((( At the same time I don't get any errors. I updated the code and the problem – elenaby Feb 21 '23 at 14:24
  • 1
    I have made my answer more explicit. Please have another look. – Mark Setchell Feb 21 '23 at 18:05
  • Nb. `b64encode()` returns a binary string (ie. bytes) so we need to convert those bytes back to ascii. See this [post](https://stackoverflow.com/q/42773386/2529954). `jpg_as_text = base64.b64encode(buffer.tobytes()).decode('ascii')` – EricLavault Feb 23 '23 at 15:55