Project

General

Profile

Patch #41919 » 0001-Add-width-and-height-when-img-src.patch

Kota Shiratsuka, 2024-12-02 15:05

View differences:

app/helpers/application_helper.rb
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)
......
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
(4-4/5)