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

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