resizing images for better performance

This commit is contained in:
Alex Corbi 2016-06-12 17:46:27 +02:00
parent d470fa6ff1
commit 3f5cded6e6
421 changed files with 906 additions and 799 deletions

View file

@ -1,10 +1,13 @@
require 'uri'
require 'faraday'
require 'yaml'
require 'mini_magick'
class Localizer
IMAGE_FIELDS = ["media_artist_url"]
RESIZED_SUFIX = "_resized.png"
IMAGES_FOLDER = File.dirname(File.dirname(__FILE__))+'/images/'
attr_reader :post_directory, :image_directory
@ -74,26 +77,54 @@ class Localizer
image_url = talk[image_field]
next unless !image_url.nil? && (image_url.start_with?('http') || image_url.start_with?('https'))
if !image_url.nil?
local_image = local_image_filename(image_url)
# Download image if it is on the internet
if image_url.start_with?('http') || image_url.start_with?('https')
local_image = local_image_filename(image_url)
begin
ensure_local_image(image_url, local_image)
rescue
puts "Error downloading locally for image: #{image_url}"
next
end
else
puts "Skipping downloading of image: #{image_url}"
end
# Create resized version if it does not existZ
if !(image_url.end_with? RESIZED_SUFIX)
local_image = image_url + RESIZED_SUFIX
resized_url = File.basename(image_url) + RESIZED_SUFIX
image_path = IMAGES_FOLDER + File.basename(resized_url)
if !File.file?(image_path)
image_to_resize = MiniMagick::Image.open(IMAGES_FOLDER + File.basename(image_url))
image_to_resize.resize('612x612')
image_to_resize.format "png"
image_to_resize.write(image_path)
local_image = File.basename(resized_url)
else
puts "Skipping resizing of image: #{resized_url}"
end
end
# Replace relative url on markdown file
if !local_image.nil? && image_url != local_image
contents = contents.gsub(image_url,local_image)
end
begin
ensure_local_image(image_url, local_image)
rescue
puts "Error downloading locally for image: #{image_url}"
next
end
# talk[image_field] = local_image
contents = contents.gsub(image_url,"/"+local_image)
end
end
puts(file)
# Step 3: replace the file itself
File.unlink(file)
File.open(file, "w", encoding: "UTF-8") { |file| file.puts contents }
end
end