Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 Carrierwave + RMagick, converting PDF to PNG changes file encoding but not extension?

I can upload a PDF and convert it to a PNG format and it renders properly in the browser via the <%= image_tag "path/to/image" %> helper. However, the actual file extension is NOT being changed from PDF to PNG. So if you download the image, it downloads as image.pdf. Once it's downloaded, if you change the extension manually to 'png' it opens image software properly on the local machine. I would like the RMagick process to automatically change the extension as well as the file format. I can write some code that strips out the PDF and adds the PNG extension when the file is saved, but it seems like I'm missing something here. I figured this is something that should be done automatically when I convert to a different format. Here's my ImageUploader.rb class. I'm using Carrierwave and RMagick.

# app/uploads/image_uploader.rb
class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick
  include Sprockets::Rails::Helper

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  process :convert_to_png

  def convert_to_png
    manipulate!(format: "png", read: { density: 400 }) do |img, index, options|
      options = { quality: 100 }
      img.resize_to_fill!(850, 1100)
      img
    end
  end

 # Add 'png' file extension so file becomes 'image.pdf.png'
 def filename
    "#{original_filename}.png" if original_filename
  end
end
like image 885
Dan L Avatar asked Oct 21 '22 11:10

Dan L


2 Answers

This is how I am handling it:

version :pdf_thumb, :if => :pdf? do
  process :thumbnail_pdf
  process :set_content_type_png

  def full_filename (for_file = model.artifact.file)
    super.chomp(File.extname(super)) + '.png'
  end
end

def thumbnail_pdf
  manipulate! do |img|
    img.format("png", 1)
    img.resize("150x150")
    img = yield(img) if block_given?
    img
  end
end

def set_content_type_png(*args)
  self.file.instance_variable_set(:@content_type, "image/png")
end
like image 53
flynfish Avatar answered Nov 03 '22 07:11

flynfish


It is a known issue: https://github.com/carrierwaveuploader/carrierwave/issues/368#issuecomment-3597643

So no, you aren't missing anything :)

like image 45
lawitschka Avatar answered Nov 03 '22 08:11

lawitschka