Home > database >  Get numpy image in php
Get numpy image in php

Time:05-23

I try to use in my web application images from a raspberry pi where all images are inserted in a RabbitMq queque. Image is published after I convert it using this function:

def im2json(im):
    imdata = pickle.dumps(im)
    jstr = json.dumps(base64.b64encode(imdata).decode('ascii'))
    return jstr

In php I tried this:

$imgString = $jsonRes->hits->hits[0]->_source->image;

echo "<img src='data:image/jpeg;base64, " . base64_encode($imgString) . "' />";

But it doesn't work, is there something that I miss because of python script? This is the result: output.

Images are stored in Elasticsearech, that's the reason I used hits->hits.

CodePudding user response:

It gets longer than I can write in comments, so trying to make an answer:

import base64
import io
import json

import numpy as np
from PIL import Image

def im2json(im):
    to_save = Image.fromarray(np.array(im))
    target = io.BytesIO()
    to_save.save(target, 'JPEG')
    target.seek(0)  # Go to the beginning of stream
    # No pickle is needed
    return json.dumps(base64.b64encode(target.read()).decode('ascii'))

And on php side

$imgString = $jsonRes->hits->hits[0]->_source->image;

echo "<img src='data:image/jpeg;base64, " . $imgString . "' />";

You shouldn't pickle BytesIO itself, you need just to base64-encode its binary content.

If it doesn't work, try removing json.dumps, I'm not sure that quotes are really needed.

  • Related