Class: Uniword::Batch::CompressImagesStage

Inherits:
ProcessingStage show all
Defined in:
lib/uniword/batch/stages/compress_images_stage.rb

Overview

Processing stage that compresses images in documents.

Responsibility: Reduce image file sizes while maintaining quality. Single Responsibility - only handles image compression.

Examples:

Use in pipeline

stage = CompressImagesStage.new(
  max_width: 1920,
  max_height: 1080,
  quality: 85
)
document = stage.process(document, context)

Instance Attribute Summary

Attributes inherited from ProcessingStage

#enabled, #options

Instance Method Summary collapse

Methods inherited from ProcessingStage

#enabled?, #name

Constructor Details

#initialize(options = {}) ⇒ CompressImagesStage

Initialize compress images stage

Parameters:

  • options (Hash) (defaults to: {})

    Stage options

Options Hash (options):

  • :max_width (Integer)

    Maximum image width in pixels

  • :max_height (Integer)

    Maximum image height in pixels

  • :quality (Integer)

    JPEG quality (0-100)

  • :preserve_aspect_ratio (Boolean)

    Maintain aspect ratio

  • :skip_small_images (Boolean)

    Skip images below min size

  • :min_size_kb (Integer)

    Minimum size to compress (KB)



27
28
29
30
31
32
33
34
35
# File 'lib/uniword/batch/stages/compress_images_stage.rb', line 27

def initialize(options = {})
  super
  @max_width = options.fetch(:max_width, 1920)
  @max_height = options.fetch(:max_height, 1080)
  @quality = options.fetch(:quality, 85)
  @preserve_aspect_ratio = options.fetch(:preserve_aspect_ratio, true)
  @skip_small_images = options.fetch(:skip_small_images, true)
  @min_size_kb = options.fetch(:min_size_kb, 100)
end

Instance Method Details

#descriptionString

Get stage description

Returns:

  • (String)

    Description



72
73
74
# File 'lib/uniword/batch/stages/compress_images_stage.rb', line 72

def description
  "Compress document images"
end

#process(document, context = {}) ⇒ Document

Process document to compress images

Parameters:

  • document (Document)

    Document to process

  • context (Hash) (defaults to: {})

    Processing context

Returns:

  • (Document)

    Processed document



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/uniword/batch/stages/compress_images_stage.rb', line 42

def process(document, context = {})
  log "Compressing images in #{context[:filename]}"

  images = collect_images(document)
  compressed_count = 0
  total_saved = 0

  images.each do |image|
    next unless should_compress_image?(image)

    saved_bytes = compress_image(image)
    if saved_bytes.positive?
      compressed_count += 1
      total_saved += saved_bytes
    end
  end

  if compressed_count.positive?
    saved_kb = (total_saved / 1024.0).round(2)
    log "Compressed #{compressed_count} image(s), saved #{saved_kb} KB"
  else
    log "No images needed compression"
  end

  document
end