2024-02-25 12:15:55 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-12-18 12:31:48 -05:00
|
|
|
module DanbooruImageResizer
|
2024-02-04 10:42:43 -05:00
|
|
|
module_function
|
2018-10-17 18:37:26 -04:00
|
|
|
|
2022-05-26 12:29:17 -04:00
|
|
|
# https://www.libvips.org/API/current/libvips-resample.html#vips-thumbnail
|
2024-02-04 10:42:43 -05:00
|
|
|
THUMBNAIL_OPTIONS = { size: :down, linear: false, no_rotate: true, export_profile: "srgb", import_profile: "srgb" }.freeze
|
2022-05-26 12:29:17 -04:00
|
|
|
# https://www.libvips.org/API/current/VipsForeignSave.html#vips-jpegsave
|
2024-06-28 12:13:52 -04:00
|
|
|
JPEG_OPTIONS = { strip: true, interlace: true, optimize_coding: true }.freeze
|
2024-02-04 10:42:43 -05:00
|
|
|
CROP_OPTIONS = { linear: false, no_rotate: true, export_profile: "srgb", import_profile: "srgb", crop: :attention }.freeze
|
2018-03-26 21:19:13 -04:00
|
|
|
|
2024-06-28 12:13:52 -04:00
|
|
|
def resize(file, width, height, resize_quality = 90, background_color: "000000")
|
|
|
|
r = background_color[0..1].to_i(16)
|
|
|
|
g = background_color[2..3].to_i(16)
|
|
|
|
b = background_color[4..5].to_i(16)
|
2018-03-26 21:19:13 -04:00
|
|
|
output_file = Tempfile.new
|
2022-05-26 12:40:20 -04:00
|
|
|
resized_image = thumbnail(file, width, height, THUMBNAIL_OPTIONS)
|
2024-06-28 12:13:52 -04:00
|
|
|
resized_image.jpegsave(output_file.path, Q: resize_quality, background: [r, g, b], **JPEG_OPTIONS)
|
2012-02-10 17:07:49 -05:00
|
|
|
|
2018-03-18 13:05:25 -04:00
|
|
|
output_file
|
2011-09-16 12:38:56 -04:00
|
|
|
end
|
2018-03-29 22:41:22 -04:00
|
|
|
|
2024-06-28 12:13:52 -04:00
|
|
|
def crop(file, width, height, resize_quality = 90, background_color: "000000")
|
2021-11-14 16:16:36 -05:00
|
|
|
return nil unless Danbooru.config.enable_image_cropping?
|
2018-07-09 13:06:20 -04:00
|
|
|
|
2024-06-28 12:13:52 -04:00
|
|
|
r = background_color[0..1].to_i(16)
|
|
|
|
g = background_color[2..3].to_i(16)
|
|
|
|
b = background_color[4..5].to_i(16)
|
2018-05-16 20:13:36 -04:00
|
|
|
output_file = Tempfile.new
|
2022-05-26 12:40:20 -04:00
|
|
|
resized_image = thumbnail(file, width, height, CROP_OPTIONS)
|
2024-06-28 12:13:52 -04:00
|
|
|
resized_image.jpegsave(output_file.path, Q: resize_quality, background: [r, g, b], **JPEG_OPTIONS)
|
2018-05-16 20:13:36 -04:00
|
|
|
|
|
|
|
output_file
|
|
|
|
end
|
2022-05-26 12:40:20 -04:00
|
|
|
|
|
|
|
# https://github.com/libvips/libvips/wiki/HOWTO----Image-shrinking
|
|
|
|
# https://www.libvips.org/API/current/Using-vipsthumbnail.md.html
|
|
|
|
def thumbnail(file, width, height, options)
|
|
|
|
Vips::Image.thumbnail(file.path, width, height: height, **options)
|
|
|
|
rescue Vips::Error => e
|
|
|
|
raise e unless e.message =~ /icc_transform/i
|
|
|
|
Vips::Image.thumbnail(file.path, width, height: height, **options.except(:import_profile))
|
|
|
|
end
|
2010-02-08 01:40:39 -05:00
|
|
|
end
|