summaryrefslogtreecommitdiff
path: root/lib/booru/image_processing/jpeg_processor.rb
blob: f40eef954f557c20e9bac523d86c6defa3aa9fa7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# frozen_string_literal: true
require_relative 'shell_helper'

module Booru
  module ImageProcessing
    class JpegProcessor < Processor
      include ShellHelper

      def pre_process
        write_log 'pre_process'
        # Perform lossy rotation on image if it has EXIF orientation field
        # (web browsers do not respect that, see http://caniuse.com/#search=image-orientation)
        image = ::MiniMagick::Image.open(@original_path)
        orientation = image.exif['Orientation']
        if orientation.to_i > 1 # 1 is the default orientation
          write_log 'Auto-oriented JPEG.'
          image.auto_orient
          image.strip # remove EXIF metadata to prevent image from being rotated again
          image.write(@original_path)
        end
      end

      def generate_version(dimensions, destination_path)
        write_log "generate_version #{dimensions} #{destination_path}"
        width, height = dimensions

        # resize JPEG to desired size and jpegtran the resized version.
        ::MiniMagick::Tool::Convert.new do |cmd|
          cmd.resize "#{width}x#{height}"
          cmd << @original_path
          cmd << destination_path
        end

        jpegtran(destination_path)
      end

      def post_process
        write_log 'post_process'
        jpegtran(@original_path)
      end
    end
  end
end