Getting Image by API, base64 encode image for image component

I may have encountered this problem just because I dont know much about web development, but I was trying to retrieve some images by an API and display them using the image component. I was having a really hard time (and no success) using the system.net.httpGet() function and then encoding that response to be used by the image component.

I used the urllib2 library and it worked.

Anyway, as there’s not examples on how to do this for an image component in the docs, maybe this example will help someone else:

Didn’t work for me:

import base64
def getImage(url, server = server, port= port, akey= token):
	fullUrl = 'http://' + server +  ':' + str(port) + url
	headers = { 
		"Token": akey
#		"Accept" : "application/json"
		}
	source = system.net.httpGet(fullUrl, headerValues = headers)
#	image = base64.encodestring( source)
#	image = Base64.encodeBytes(source.decode('utf-8'))
	image = base64.b64encode(source)
	return image

What did work:

import urllib2
import base64
def getImage2(url, server = server, port= port, akey= token):
	headers = { 
			"Token": akey
			}
	fullUrl = 'http://' + server +  ':' + str(port) + url	
	request = urllib2.Request(fullUrl, headers=headers)
	contents = urllib2.urlopen(request).read()
	data = base64.b64encode(contents)
	return data

Last you need to tell the image what to do with this, so in the source binding on the image component, you need something like this
'data:image/jpeg;base64, ' + (data from the getImage2 function above).

2 Likes

Entirely within Ignition/Java modules (potentially a tiny bit faster) this should work:

from com.inductiveautomation.ignition.common import Base64
client = system.net.httpClient()

def getImage(url, token, headers = None):
	headers = headers if headers is not None else {}
	headers["Token"] = token
	response = client.get(url, headers=headers)
	if response.good:
		return response.body

def encodeImage(data, filetype):
	return "data:image/{};base64,{}".format(filetype, Base64.encodeBytes(data))

At the call site it’d be something like:

image = api.getImage("http://myServiceUrl/api/images", token)
if image is not None:
	return api.encodeImage(image, "jpeg")
2 Likes