简体   繁体   中英

Converting pdf to image using rmagick produces black background image

I am using Active Storage to upload the pdf files and i need to convert it to image and save it as a attachment. Below is the code i used for this purpose, but it gives me the converted image with black background.

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

Anyone has any solution to this? I am new to Rmagick.

ruby '2.6.5'

rails '6.0.1'

gem 'rmagick'

RMagick renders the alpha channel as black. If the alpha channel is removed the image background will render in white.

The alpha channel can be removed with the following snippet:

jpg = Magick::ImageList.new(URI.open(pdf).path)
jpg.each { |j| j.alpha(Magick::RemoveAlphaChannel) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM