Generating Open Graph Images with SVG partial and Vips

Curated ago by @jeremysmithco

Description

I found a way to generate custom Open Graph images for Sample files on this site using an SVG partial that is rendered and converted to PNG by ImageProcessing::Vips.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class CreateSampleFileImage
  def initialize(sample_file)
    @sample_file = sample_file
  end

  def create
    svg_string = ApplicationController.render(
      partial: "sample_files/sample_file", format: "svg", assigns: { sample_file: sample_file }
    )

    svg_file = Tempfile.new
    begin
      svg_file.write(svg_string)

      pipeline = ImageProcessing::Vips
      pipeline.source(svg_file).convert("png").call
    ensure
       svg_file.close
       svg_file.unlink
    end
  end

  private

  attr_reader :sample_file
end

The service object renders the partial to string and converts it to PNG with Vips.