[英]What is the proper way to preview a file (image or pdf) using active storage?
[英]Converting pdf to image using rmagick produces black background image
我正在使用 Active Storage 上傳 pdf 文件,我需要將其轉換為圖像並將其保存為附件。 下面是我用於此目的的代碼,但它給了我轉換后的黑色背景圖像。
project_file.rb
class ProjectFile < ApplicationRecord
has_many_attached: files
end
converted_image.rb
class ConvertedImage < ApplicationRecord
has_one_attached: image
end
some_controller.rb
def show
pdf = url_for(ProjectFile.last.files.first)
PdfToImage.new(pdf).perform
end
pdf_to_image.rb
class PdfToImage
require 'rmagick'
require 'open-uri'
attr_reader :pdf
def initialize(pdf)
@pdf = pdf
end
def perform
jpg = Magick::ImageList.new(URI.open(pdf).path)
file = Tempfile.new(['converted', '.jpg'])
jpg.write(file.path)
image = File.open(file)
ConvertedImage.last.image.attach(io: image, filename: "converted.jpg", content_type: 'application/jpg')
image.close
end
end
有人對此有任何解決方案嗎? 我是 Rmagick 的新手。
ruby '2.6.5'
導軌'6.0.1'
寶石'rmagick'
RMagick 將 Alpha 通道渲染為黑色。 如果 alpha 通道被移除,圖像背景將呈現為白色。
可以使用以下代碼段刪除 Alpha 通道:
jpg = Magick::ImageList.new(URI.open(pdf).path)
jpg.each { |j| j.alpha(Magick::RemoveAlphaChannel) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.