From 92c5a53bd7e89fcd9d7a6a6916c05bfe52712bc9 Mon Sep 17 00:00:00 2001 From: Kota Shiratsuka Date: Sun, 24 Nov 2024 14:42:46 +0900 Subject: [PATCH 1/2] Add width and height when img src --- app/helpers/application_helper.rb | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index bac8da266..62d29183d 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -990,10 +990,14 @@ module ApplicationHelper end if attachments.present? title_and_alt_re = /\s+(title|alt)="([^"]*)"/i + style_attr_re = /\s+style="([^"]*)"/i text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpe|jpeg|png|webp))"([^>]*)/i) do |m| filename, ext, other_attrs = $1, $2, $3 + # Check if style attribute exists + has_style = other_attrs =~ style_attr_re + # search for the picture in attachments if found = Attachment.latest_attach(attachments, CGI.unescape(filename)) image_url = download_named_attachment_url(found, found.filename, :only_path => only_path) @@ -1003,13 +1007,35 @@ module ApplicationHelper title_and_alt = other_attrs.scan(title_and_alt_re).to_h other_attrs.gsub!(title_and_alt_re, '') + # Process dimensions and scaling + width, height = nil, nil + image = MiniMagick::Image.open(found.diskfile) + width, height = image.width, image.height + + # Adjust dimensions for @2x, @3x, etc. + if filename =~ /@(\d+)x\./ + scale_factor = $1.to_i + width /= scale_factor + height /= scale_factor + end + + # Resize if width exceeds 1000px while maintaining aspect ratio + if width > 1000 + scale = 800.0 / width + width = 800 + height = (height * scale).round + end + + # Add width and height to the img tag only if style attribute is absent + dimension_attrs = (!has_style && width && height) ? " width=\"#{width}\" height=\"#{height}\"" : "" + title_and_alt_attrs = if !desc.blank? && title_and_alt['alt'].blank? " title=\"#{desc}\" alt=\"#{desc}\"" else # restore original title and alt attributes " #{title_and_alt.map { |k, v| %[#{k}="#{v}"] }.join(' ')}" end - "src=\"#{image_url}\"#{title_and_alt_attrs} loading=\"lazy\"#{other_attrs}" + "src=\"#{image_url}\"#{title_and_alt_attrs}#{dimension_attrs} loading=\"lazy\"#{other_attrs}" else m end -- 2.47.1