Rails,Active Storage,MiniMagick-将PDF页面转换为图像(.png,.jpg等)并上传到活动存储中

问题描述 投票:0回答:1

[我正在使用滑轨,活动存储和minimagick尝试将多页PDF转换为单个PNG图像,然后将图像存储在活动存储中。

我已经能够使用MiniMagick成功加载PDF并将页面转换为png图像。但是,我只能让Minimagic将png图像存储在app / assets / images目录中(而不是将png图像存储为活动存储附件)。

有人知道如何让MiniMagick使用活动存储来存储图像吗?

这是我正在使用的代码:

# Doc model with active storage attachments
class Doc < ApplicationRecord
  has_one_attached :pdf         #PDF file to upload
  has_many_attached :pdf_pages  #PNG image for each page of the PDF
end 

# PrepareDocs controller manages saving a PNG image of each PDF page. 
# NOTE: at this point, the PDF has already been attached to the @doc instance. 
# Now we are trying to create the PNG images of each page of the PDF
class PrepareDocsController < ApplicationController
  def show
    # Load @doc
    @doc = Doc.find(params[:id])
    # Get PDF from @doc
    mini_magic_pdf = MiniMagick::Image.open(ActiveStorage::Blob.service.send(:path_for, @doc.pdf.key))

    # Save first page of doc.pdf as a PNG (later I will update this to convert every page to a PNG, but I'm starting on page 1 for now)
    MiniMagick::Tool::Convert.new do |convert|
      # Prepare formatting for PNG image
      convert.background "white"
      convert.flatten
      convert.density 150
      convert.quality 100
      # Save PNG Image - This successfully creates a PNG of the first page, but I don't want to store it in my assets.
      convert << mini_magic_pdf.pages.first.path
      convert << "app/assets/images/page_1.png"   # This probably needs to be changed so that we are not storing in the app/assets/imdages directory
      # [??? insert additional code to attach the png image to @doc.pdf_pages using active storage instead of to the images directory?]
      # NOTE: if I try to access the newly created png in my views, I get "incorrect signature" OR "asset not available in asset pipeline" errors
    end

  end
end

任何帮助将不胜感激!谢谢!

ruby-on-rails rails-activestorage minimagick
1个回答
0
投票

app/assets是资产来源的目录,资产编译期间(通常在部署时完成),其中的图像会复制到public/assets,以便能够访问创建的图像-将它们存储在public中的某个位置,例如public/converted/page_1.png(它将具有路径/converted/page_1.png

[MiniMagick只是ImageMagick命令行实用程序的包装,因此,在将结果上传到activestorage之前,您需要将结果保存在一个临时位置,然后使用类似的内容:

converted_file_path = File.join(Dir.tmpdir, Dir::Tmpname.make_tmpname(["prefix-", ".png"], nil))
... # do convertation
@doc.pdf_pages.attach(io: File.open(converted_file_path), filename: 'page1.png')
FileUtils.rm(converted_file_path)
© www.soinside.com 2019 - 2024. All rights reserved.