so i created a PNG image using chunky_png. i don't want to save this image, because its only useful for this one request, so i'm trying to save this image as an instance variable and displaying it in my view.
the problem is that this results in an invalid byte sequence in UTF-8
error in my view.
what i did:
# controller
@img = source_img.resize(200, 200).to_string
#view
<img src="data:image/png;base64,<%= @img %>" />
debugging the @img variable with raise @img.to_yaml
outputs me the correct string, f.e.:
--- !binary |-
iVBORw0KGgoAAAANSUhEUgAAAMgAAADIAQAAAACFI5MzAAACP0lEQVR4nO1Y
QY6jQAy0AxJ9a34AH8l29lmRhgDJSDxrwsxHmh80N5Ag3urkjFZabTw5TJ+g
HclWUa6ys5Ots6Ot8xP5/xFhnJIGxo/GdDD9HC+al6iNMpGFVie3kXOiyZET
8bq49cAipRn5bVXOB+CVPiXPXyMRhQb1PDvPRmQZAMWOam/cN1TgpKFEyIVT
pENLDF6oVoCuSCkdSIokEJnICy41K+AojX4psutY5+8011m80O1T4YpXxsOJ
3mjqo2A8Jc+/RD7txVNhWFrJPDnTF41uBfPvoXKJHw/jjt7QLMThqKuj2Ufe
+bUEFDeigtykr1UsVQkT2TP0cjA0H6wuR4VPkKilmMCDACjISmhLXc/64Ap+
mp3RJZ3IFTVpe9aXXHxawKzOY/Ss8WCVHX2u7hjYNa/yxNsWSrEULzJT0Cd1
XgToXEDWx/WgWRtPHKkZGSJ86ccDHjqvy9E1ryHfKORkmwJ+5u7NoqoUoXXQ
axqTYS6Ng2jWukoBD6/7qI+2sc2AmUIKLnUxkHzFMDURVXdHx3hT97pd8hU6
v9B8Ghs0qOnhIO9PybMZQRuumKTM42Ii3o2zew2lYLnBvRKP9ryErjeEd10/
fexmaznti8ZWbopoJV5XKeIGJp6TUEEyDGVXZbV8bGCMqRPbTyQnlpDjNzAk
gZXbNhxLINKH5+XZjsxsJD8DAwjGPtf+CnEDI8xVIX4HQ4aDtlLEDSzx5hdk
M77FuUp5/9mKPHazu5LX97+wMH42qhX8RP4AQpEyh+7r4x0AAAAASUVORK5C
YII=
copiing this string manually into the img tag displays the image correctly.
any ideas whats going wrong here? other ideas of displaying this image directly without saving?
thanks in advance! if something is unclear, PLEASE leave a comment.
ChunkyPNG actually comes with a built-in function to do just this: to_data_url
.
# controller
@img = source_img.resize(200, 200)
# view
<img src="<%= @img.to_data_url %>" />
It's implemented like this:
['data:image/png;base64,', @img.to_blob].pack('A*m').gsub(/\n/, '')
Make sure you're using the latest version of ChunkyPNG.
The @wvanbergen way gave me some errors, but I changed a little and it worked.
#controller
@png = qr.to_img.resize(250,250).to_data_url
#view
<%= image_tag @png %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With