Home > other >  How to convert Base64DataURL to base64-encoded image bytes
How to convert Base64DataURL to base64-encoded image bytes

Time:04-11

I'm calling in js canvas.toDataURL(); sending it to my server from there I want to send it with boto3client.('rekognition', ... ,...) how can I change the formate in python assuming I have the data in a variable.

#image is a 10 by 10 red square can be displayed with adding data as src of a HTML image tag
data = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs 9AAAAGElEQVQYV2P8z8AARIQB46hCfIFE/eABAGX8E/e8eQLYAAAAAElFTkSuQmCC"
client = boto3.client('rekognition',
                       aws_access_key_id= access_key_id,
                       aws_secret_access_key = secret_access_key_id)

response = client.detect_labels(Image = { 'Bytes': data }, MaxLabels = 10)

botocore.errorfactory.InvalidImageFormatException: An error occurred (InvalidImageFormatException) when calling the DetectLabels operation: Request has invalid image format

this seems related to AWS Rekognition detect label Invalid image encoding error but also kinda hacky

example input:

"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs 9AAAAGElEQVQYV2P8z8AARIQB46hCfIFE/eABAGX8E/e8eQLYAAAAAElFTkSuQmCC"

example output:

b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f\x17\x18\x16\x14\x18\x12\x14\x15\x14\xff\xdb\x00C\x01\x03\x04\x04\x05\x04\x05\t\x05\x05\t\x14\r\x0b\r\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14...'

CodePudding user response:

from datauri import DataURI
tosend = DataURI(data)
tosend = tosend.data
client = boto3.client('rekognition',
                   aws_access_key_id= access_key_id,
                   aws_secret_access_key = secret_access_key_id)

response = client.detect_labels(Image = { 'Bytes': tosend }, MaxLabels = 10)
  • Related