我之前使用CarrierWave和ImageMagick将PDF分成图像,使用如下所示:

def pdf_to_imgs
  manipulate! do |img, index|
    image.format = 'png'
    image.write("path/to/images/image-#{index}.png")
  end
end

使用Rails 5.2,ActiveStorage似乎是上传的方式,因此我尝试迁移所有内容 .

我有以下内容,它在技术上有效:

def pdf_to_imgs
  path = Rails.application.routes.url_helpers.rails_blob_url(self.pdf)
  page_count = MiniMagick::Image.open(path).pages.count
  pipeline = ImageProcessing::MiniMagick.source(path).convert("jpg")
  images = page_count.times.map do |page_number|
    pipeline.loader(page: page_number).call
  end
  images.each_with_index do |slide, i|
    self.images.attach(io: File.open(pdf), filename: "pdf-#{i}.jpg", content_type: "image/jpg")
  end
end

但是,我很好奇这是否是最好的方法,或者是否有更好的方法?例如,我希望将数组传递给attach方法,但是出现了错误 . 上述过程似乎也需要很长时间才能执行(尽管有大型PDF文件) .

并且,控制台挂起“Performed ActiveStorage :: AnalyzeJob”,但我认为这只是因为它是一个异步工作 .

在此先感谢您的帮助!