1
0

image_extractor.rb 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # frozen_string_literal: true
  2. require 'mime/types/columnar'
  3. module Paperclip
  4. class ImageExtractor < Paperclip::Processor
  5. def make
  6. return @file unless options[:style] == :original
  7. image = extract_image_from_file!
  8. unless image.nil?
  9. begin
  10. attachment.instance.thumbnail = image if image.size.positive?
  11. ensure
  12. # Paperclip does not automatically delete the source file of
  13. # a new attachment while working on copies of it, so we need
  14. # to make sure it's cleaned up
  15. begin
  16. image.close(true)
  17. rescue Errno::ENOENT
  18. nil
  19. end
  20. end
  21. end
  22. @file
  23. end
  24. private
  25. def extract_image_from_file!
  26. dst = Tempfile.new([File.basename(@file.path, '.*'), '.png'])
  27. dst.binmode
  28. begin
  29. command = Terrapin::CommandLine.new('ffmpeg', '-i :source -loglevel :loglevel -y :destination', logger: Paperclip.logger)
  30. command.run(source: @file.path, destination: dst.path, loglevel: 'fatal')
  31. rescue Terrapin::ExitStatusError
  32. dst.close(true)
  33. return nil
  34. rescue Terrapin::CommandNotFoundError
  35. raise Paperclip::Errors::CommandNotFoundError, 'Could not run the `ffmpeg` command. Please install ffmpeg.'
  36. end
  37. dst
  38. end
  39. end
  40. end