FIX: don't try to optimize large PNGs (takes too much time)

This commit is contained in:
Régis Hanol
2016-02-22 12:57:24 +01:00
parent 5f747a74a1
commit 4d981cec53
3 changed files with 35 additions and 20 deletions

View File

@@ -51,13 +51,16 @@ class UploadsController < ApplicationController
render nothing: true, status: 404
end
MAXIMUM_UPLOAD_SIZE ||= 10.megabytes
DOWNSIZE_RATIO ||= 0.8
def create_upload(type, file, url)
begin
# ensure we have a file
if file.nil?
# API can provide a URL
if url.present? && is_api?
tempfile = FileHelper.download(url, 10.megabytes, "discourse-upload-#{type}") rescue nil
tempfile = FileHelper.download(url, MAXIMUM_UPLOAD_SIZE, "discourse-upload-#{type}") rescue nil
filename = File.basename(URI.parse(url).path)
end
else
@@ -69,20 +72,21 @@ class UploadsController < ApplicationController
return { errors: I18n.t("upload.file_missing") } if tempfile.nil?
# allow users to upload (not that) large images that will be automatically reduced to allowed size
uploaded_size = File.size(tempfile.path)
if SiteSetting.max_image_size_kb > 0 && FileHelper.is_image?(filename) && uploaded_size > 0 && uploaded_size < 10.megabytes
attempt = 2
allow_animation = type == "avatar" ? SiteSetting.allow_animated_avatars : SiteSetting.allow_animated_thumbnails
while attempt > 0
downsized_size = File.size(tempfile.path)
break if downsized_size > uploaded_size
break if downsized_size < SiteSetting.max_image_size_kb.kilobytes
image_info = FastImage.new(tempfile.path) rescue nil
w, h = *(image_info.try(:size) || [0, 0])
break if w == 0 || h == 0
dimensions = "#{(w * 0.8).floor}x#{(h * 0.8).floor}"
OptimizedImage.downsize(tempfile.path, tempfile.path, dimensions, filename: filename, allow_animation: allow_animation)
attempt -= 1
if SiteSetting.max_image_size_kb > 0 && FileHelper.is_image?(filename)
uploaded_size = File.size(tempfile.path)
if 0 < uploaded_size && uploaded_size < MAXIMUM_UPLOAD_SIZE && Upload.should_optimize?(tempfile.path)
attempt = 2
allow_animation = type == "avatar" ? SiteSetting.allow_animated_avatars : SiteSetting.allow_animated_thumbnails
while attempt > 0
downsized_size = File.size(tempfile.path)
break if uploaded_size < downsized_size || downsized_size < SiteSetting.max_image_size_kb.kilobytes
image_info = FastImage.new(tempfile.path) rescue nil
w, h = *(image_info.try(:size) || [0, 0])
break if w == 0 || h == 0
dimensions = "#{(w * DOWNSIZE_RATIO).floor}x#{(h * DOWNSIZE_RATIO).floor}"
OptimizedImage.downsize(tempfile.path, tempfile.path, dimensions, filename: filename, allow_animation: allow_animation)
attempt -= 1
end
end
end