Shun Yamada
Shun Yamada

Reputation: 979

MiniMagick Error: How to generate OG image with MiniMagick

So I'm working on a Rails application. It generates OG image drawn to text a user inputs. For example, you input "Hello world", save it, and then an application generates an OG image written to "Hello world".

But it occurs to this error:

apps/controllers/reviews_controller.rb

include SetupOgbImage

def create
  @review = current_user.active_reviews.create(create_params)
  @review.image = build(@review.content)
  if @review.save
    flash[:success] = "Successfully added a review!"
    redirect_to review_path(id: @review.id)
  else
    flash[:alert] = "Failed to add a review."
    redirect_to user_path(id: @review.reviewed_id)
  end
end

apps/controllers/concerns/setup_ogb_image.rb

module SetupOgbImage
    def build(text)
        text = prepare_text(text)
        img = MiniMagick::Image.open(Settings.ogb.base_image_path)
        img.combine_options do |config|
        config.font Settings.ogb.font_path
        config.fill Settings.ogb.color
        config.gravity Settings.ogb.gravity
        config.pointsize Settings.ogb.font_size
        config.draw "text #{Settings.ogb.text_position} #{text}"
        end
        img
    end

    def prepare_text(text)
        text.scan(/.{1,#{Settings.ogb.indention_count}}/)[0...Settings.ogb.row_limit].join("\n")
    end
end

settings.yml

ogb:
  base_image_path: ./app/assets/images/ogb_bg_image.png
  gravity: center
  text_position: "0,30"
  font_path: ./app/assets/fonts/Hind-Medium.ttf
  font_size: 24
  color: "#fff"
  indention_count: 60
  row_limit: 10
format:
  uuid: !ruby/regexp /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/

Upvotes: 0

Views: 52

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

You should put the text into quotes, otherwise, the shell that is, in turn, executing the command, treats “Hello” and “world!” as two different arguments in call to mogrify:

#                                               ⇓       ⇓
config.draw "text #{Settings.ogb.text_position} '#{text}'"

Upvotes: 1

Related Questions