首页 > 解决方案 > 如何使用 gem MiniMagik 管理图像质量

问题描述

我正在开发一个应用程序,该应用程序从 Ruby on Rails 4 中的 Express Carriers 获取货件标签。目前,我正在使用 UPS API 及其标签,即 GIF 图像。为了能够生成包含 GIF 标签的 PDF,我使用了不支持 GIF 的 Prawn。所以GIF被转换成PNG。我可以拿到标签,但是当我打印出来时,质量非常低,很难阅读标签内的内容。我需要了解如何添加更好的质量,否则标签无法使用它。

我正在学习的课程:

class UPSLabelConsolidation
  attr_reader :base64_encoded_gif_labels

  def initialize(base64_encoded_gif_labels)
    @base64_encoded_gif_labels = base64_encoded_gif_labels
  end

  def perform!
    identifier = SecureRandom.hex(3)

    tmp_label_files = base64_encoded_gif_labels.each_with_index.map do |base64_encoded_gif_label, index|
      tmp_label_file = Tempfile.new(["ups-label-#{identifier}-#{index}", ".png"], Rails.root.join("tmp"))
      tmp_label_file.binmode

      image = MiniMagick::Image.read(Base64.decode64(base64_encoded_gif_label), "gif")

      image.combine_options do |b|
        b.rotate "90" # Rotate 90-degrees clockwise
        b.crop "800x1000+0+0" # Crop ~200px whitespace from the bottom of the label
      end

      image.format("png") # Prawn does not support GIF, so we convert it here.
      image.write(tmp_label_file.path)

      tmp_label_file.rewind

      tmp_label_file
    end

    new_page = false
    @pdf = Prawn::Document.new(page_size: [297, 390], margin: 20, page_layout: :portrait) # Margin is ~0.7cm

    tmp_label_files.each do |label_file|
      @pdf.start_new_page if new_page
      @pdf.image label_file, width: 250, position: :left # Width is ~8.8cm
      new_page = true
    end
  end

  def write!(path)
    if @pdf
      @pdf.render_file(path)
    else
      raise "`#perform!` before `#write!`"
    end
  end
end

标签: ruby-on-railsimagemagickprawn

解决方案


推荐阅读