简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM