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.

thumbnail.rb 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2017 Jean-Philippe Lang
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # of the License, or (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. require 'fileutils'
  18. require 'mimemagic'
  19. module Redmine
  20. module Thumbnail
  21. extend Redmine::Utils::Shell
  22. CONVERT_BIN = (Redmine::Configuration['imagemagick_convert_command'] || 'convert').freeze
  23. ALLOWED_TYPES = %w(image/bmp image/gif image/jpeg image/png)
  24. # Generates a thumbnail for the source image to target
  25. def self.generate(source, target, size)
  26. return nil unless convert_available?
  27. unless File.exists?(target)
  28. # Make sure we only invoke Imagemagick if the file type is allowed
  29. unless File.open(source) {|f| ALLOWED_TYPES.include? MimeMagic.by_magic(f).try(:type) }
  30. return nil
  31. end
  32. directory = File.dirname(target)
  33. unless File.exists?(directory)
  34. FileUtils.mkdir_p directory
  35. end
  36. size_option = "#{size}x#{size}>"
  37. cmd = "#{shell_quote CONVERT_BIN} #{shell_quote source} -auto-orient -thumbnail #{shell_quote size_option} #{shell_quote target}"
  38. unless system(cmd)
  39. logger.error("Creating thumbnail failed (#{$?}):\nCommand: #{cmd}")
  40. return nil
  41. end
  42. end
  43. target
  44. end
  45. def self.convert_available?
  46. return @convert_available if defined?(@convert_available)
  47. @convert_available = system("#{shell_quote CONVERT_BIN} -version") rescue false
  48. logger.warn("Imagemagick's convert binary (#{CONVERT_BIN}) not available") unless @convert_available
  49. @convert_available
  50. end
  51. def self.logger
  52. Rails.logger
  53. end
  54. end
  55. end