Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Active Storage render tiny image as base64

I want to take an image that has already been uploaded and render the image as a small variant, then output that as a base 64 string.

I cannot seem to get the transformed image, I keep getting the original unprocessed image when I try this:

image.attachment.variant( resize_to_fill: [10, 10], convert: :png ).processed.blob.open do |tempfile|
  puts 'data:image/png;base64,' + Base64.strict_encode64(tempfile.read)
end

This is returning the data as the full image, not the 10x10 tiny square image. It seems like calling .blob on it returns the original image and not the processed one.

like image 302
JP Silvashy Avatar asked May 17 '26 15:05

JP Silvashy


1 Answers

Try this:

  variation = ActiveStorage::Variation.new(resize_to_fit: [10, 10])

  image.open do |input|
    variation.transform(input, format: "png") do |output|
      puts 'data:image/png;base64,' + Base64.strict_encode64(output.read)
    end
  end
like image 159
Rodrigo Dias Avatar answered May 19 '26 04:05

Rodrigo Dias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!