Speed up image processing with CarrierWave

1. Compress images on the frontend before submitting them to the API

2. Use a worker to create thumbnails or preview versions when needed

Example: Create a thumbnail from the original image URL

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
require "open-uri"
require "mini_magick"

class ImageOptimizerService
def initialize(media_file_id)
@media_file = MediaFile.find(media_file_id)
end

def perform
content = URI.open(@media_file.file_url)
width = 100
height = 100
quality = 30

img = MiniMagick::Image.read(content)
w_original = img[:width].to_f
h_original = img[:height].to_f

# check proportions
op_resize = w_original * height < h_original * width ? "#{width.to_i}x" : "x#{height.to_i}"

img.combine_options do |i|
i.resize(op_resize)
i.gravity(:center)
i.quality quality.to_s if quality.to_i > 1 && quality.to_i < 100
i.crop "#{width.to_i}x#{height.to_i}+0+0!"
end

img.format("jpg")

media_file = MediaFile.create(file: img)
end
end

3. Use CloudFront

Create AWS CloudFront and get the CDN endpoint

1
config.asset_host = "https://your_random_string.cloudfront.net"

4. Override default methods

1
2
3
4
5
6
7
def move_to_cache
true
end

def move_to_store
true
end