Skip to content

Instantly share code, notes, and snippets.

@avdgaag
Created September 9, 2009 10:03
Show Gist options
  • Save avdgaag/183617 to your computer and use it in GitHub Desktop.
Save avdgaag/183617 to your computer and use it in GitHub Desktop.
Loop through all PHP files and add width and height to images that do not have them
pattern = /<img\s+((alt|border|class|id|src|usemap|hspace|vspace)="[^"]+"\s*)+>/
# Invoke sips to try and find the image's original dimensions
# This returns both the widht and height.
def get_original_size_for(image)
output = %x{sips -g pixelWidth -g pixelHeight "#{image}"}
if output.scan(/pixelWidth:[^\d]*(\d+).*pixelHeight:[^\d](\d+)/im)
return $1, $2
else
exit_show_tool_tip "Could not get image size from #{output.inspect}"
end
end
Dir['../../**/*.php'].each do |filename|
if (lines = File.readlines(filename)).grep(pattern).any?
File.open filename, 'w+' do |f|
lines.map! do |line|
if line =~ pattern
puts line
line.gsub(/src="(.+?)"/) do |match|
filename = File.join(File.dirname(__FILE__), '..', '..', $1)
if File.exists?(filename)
match + (' width="%d" height="%d"' % get_original_size_for(filename))
else
puts 'File not found: ' + filename
match
end
end
else
line
end
end
f.puts lines
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment