mirror of
https://github.com/discourse/discourse.git
synced 2024-11-29 20:24:05 -06:00
REFACTOR: Reduce repetition in code.
This commit is contained in:
parent
03762e2828
commit
60f1169077
@ -105,6 +105,9 @@ class Upload < ActiveRecord::Base
|
||||
DistributedMutex.synchronize("upload_#{user_id}_#{filename}") do
|
||||
# do some work on images
|
||||
if FileHelper.is_image?(filename) && is_actual_image?(file)
|
||||
# retrieve image info
|
||||
w, h = FastImage.size(file) || [0, 0]
|
||||
|
||||
if filename[/\.svg$/i]
|
||||
# whitelist svg elements
|
||||
doc = Nokogiri::XML(file)
|
||||
@ -112,20 +115,15 @@ class Upload < ActiveRecord::Base
|
||||
File.write(file.path, doc.to_s)
|
||||
file.rewind
|
||||
else
|
||||
# ensure image isn't huge
|
||||
w, h = FastImage.size(file) || [0, 0]
|
||||
if w * h >= SiteSetting.max_image_megapixels * 1_000_000
|
||||
upload.errors.add(:base, I18n.t("upload.images.larger_than_x_megapixels", max_image_megapixels: SiteSetting.max_image_megapixels))
|
||||
return upload
|
||||
end
|
||||
|
||||
# fix orientation first
|
||||
fix_image_orientation(file.path) if should_optimize?(file.path)
|
||||
fix_image_orientation(file.path) if should_optimize?(file.path, [w, h])
|
||||
end
|
||||
|
||||
# retrieve image info
|
||||
w, h = FastImage.size(file) || [0, 0]
|
||||
|
||||
# default size
|
||||
width, height = ImageSizer.resize(w, h)
|
||||
|
||||
@ -156,7 +154,7 @@ class Upload < ActiveRecord::Base
|
||||
end
|
||||
|
||||
# optimize image (except GIFs, SVGs and large PNGs)
|
||||
if should_optimize?(file.path)
|
||||
if should_optimize?(file.path, [w, h])
|
||||
ImageOptim.new.optimize_image!(file.path) rescue nil
|
||||
# update the file size
|
||||
filesize = File.size(file.path)
|
||||
@ -225,11 +223,13 @@ class Upload < ActiveRecord::Base
|
||||
|
||||
LARGE_PNG_SIZE ||= 3.megabytes
|
||||
|
||||
def self.should_optimize?(path)
|
||||
def self.should_optimize?(path, dimensions = nil)
|
||||
# don't optimize GIFs or SVGs
|
||||
return false if path =~ /\.(gif|svg)$/i
|
||||
return true if path !~ /\.png$/i
|
||||
w, h = FastImage.size(path) || [0, 0]
|
||||
|
||||
dimensions ||= (FastImage.size(path) || [0, 0])
|
||||
w, h = dimensions
|
||||
# don't optimize large PNGs
|
||||
w > 0 && h > 0 && w * h < LARGE_PNG_SIZE
|
||||
end
|
||||
|
Loading…
Reference in New Issue
Block a user