danielsmith1789
danielsmith1789

Reputation: 672

HTTParty response: GET image and convert bytes to base64 image data url

I am trying to download an image, and then return a base64 data url.

img = HTTParty.get('https://via.placeholder.com/150')
=> "\x89PNG\r\n\x1A\n\x00\x00\x00..."

base64_img = Base64.encode64(img)
=> "iVBORw0KGgoAAAANSUhEUgAAAJYAAACWBAMAAADOL2zRAAA..."

data_url = "data:image/png;base64," + base64_img
=> "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJYAAA..."

When I paste that image into my browser it should render. Yet it is not valid. What am I doing wrong, any insight would be greatly appreciated.

Upvotes: 1

Views: 969

Answers (1)

Paweł Dąbrowski
Paweł Dąbrowski

Reputation: 754

Use Base64.strict_encode64(img) instead of encode64(img)

Upvotes: 3

Related Questions