You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.1 KiB

  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. ::Av.logger = Paperclip.logger
  27. cli = ::Av.cli
  28. dst = Tempfile.new([File.basename(@file.path, '.*'), '.png'])
  29. dst.binmode
  30. cli.add_source(@file.path)
  31. cli.add_destination(dst.path)
  32. cli.add_output_param loglevel: 'fatal'
  33. begin
  34. cli.run
  35. rescue Cocaine::ExitStatusError, ::Av::CommandError
  36. dst.close(true)
  37. return nil
  38. end
  39. dst
  40. end
  41. end
  42. end