Rails API create QR code and store image in active_storage

Viewed 673

I am working on Rails 6 API where I need to generate the QR code image and save that image to S3 using active_storage.

I am using rqrcode gem for this which gives me the SVG string. How can I convert the SVG string into the image and store that image to S3 using active_storage?

Following is my code

Controller

qrcode = RQRCode::QRCode.new("#{@order.id}")
    svg = qrcode.as_svg(
      offset: 0,
      color: '000',
      shape_rendering: 'crispEdges',
      module_size: 6,
      standalone: true
    )

I should also generate the png image using

png = qrcode.as_png(
      bit_depth: 1,
      border_modules: 4,
      color_mode: ChunkyPNG::COLOR_GRAYSCALE,
      color: 'black',
      file: nil,
      fill: 'white',
      module_px_size: 6,
      resize_exactly_to: false,
      resize_gte_to: false,
      size: 120
    )

But while storing I got the following error

ArgumentError (Could not find or build blob: expected attachable, got <ChunkyPNG::Image 120x120 [

Looking for a way to generate the image from the svg string or png file.

Thanks.

note: frontend is react-native

1 Answers

I was able to achieve this by following the answer here.

In short, after you generate the png, you can attach it to your model like so: @model.qr_code.attach(io: StringIO.new(png.to_s), filename: "filename.png")

Related