Skip to content

Instantly share code, notes, and snippets.

@bbasseri
Created April 29, 2012 12:37
Show Gist options
  • Save bbasseri/2550150 to your computer and use it in GitHub Desktop.
Save bbasseri/2550150 to your computer and use it in GitHub Desktop.
Converting PDF to multiple PNG files, and creating a model for each PNG.
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
include Magick
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
process :pdf? => (self)
version :thumb do
process :resize_to_fill => [400,500]
end
version :profile do
# process :convert => 'png'
process :resize_to_fit => [200,300]
end
protected
def pdf?(new_file)
if self.current_path.include? 'pdf'
puts "it is pdf"
converting(new_file)
else
puts "it is not pdf"
end
end
def converting(new_file)
i = 0
manipulate! :if => :pdf? do |image|
pdf = ImageList.new image.filename
jpg = pdf[i]
@page = Page.new
jpg.write("#{Rails.root}/public/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}/p#{i+1}.png")
# @page.presentation_id = ""
@page.image = "p#{i+1}.png"
@page.save
i = i + 1
puts "page #{i}"
jpg
end
end
end
@ibrahima
Copy link

ibrahima commented May 2, 2012

Do you know why it is that you have to call converting inside the conditional of a version block for it to work properly? Otherwise it seems to save the images in the wrong directory.

@bbasseri
Copy link
Author

bbasseri commented May 3, 2012

@ibrahima, Process :converting runs before everything, and performs different procedures on the file uploaded, this occurs even before the model is created. So because the model is not created yet, there is no model.id therefore the location it is saved in is not correct. But I think version occurs after the model is created, therefore it should have all the correct attributes of the model, such as the id. This code was not fulfilling my requirements so I had to create another uploader. will post a link for it soon.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment