私は最終的に解決策、Pythonスクリプトを思い付いた、ここでそれは(私はgithub gist)をも作成しましたです
ここでは、コードの背後にある主要なアイデアです:すべての上
- 反復ブログの記事。
- は各ポスト内のすべての
img
のタグを検索します。
- が
src
属性の内容を抽出します。
- 画像を開きますそのサイズを抽出する。
img
の画像のサイズはwidth
とheight
となります。
コード:ちょうどあなたのマシンでスクリプトを作成し、あなたの記事がどこにあるか指すようにpath
変数を変更
を使用する方法
#!/bin/python
from BeautifulSoup import BeautifulSoup
from os.path import basename, splitext
from PIL import Image
import glob
# Path where the posts are, in markdown format
path = "/ruta/ficheros/*.md"
# Iterate over all posts
for fname in glob.glob(path):
# Open the post
f = open(fname)
# Create a BeautifulSoup object to parse the file
soup = BeautifulSoup(f)
f.close()
# For each img tag:
for img in soup.findAll('img'):
if img != None:
try:
if img['src'].startswith("/assets") == True:
# Open the image
pil = Image.open("/ruta/carpeta/imagenes" + img['src'])
# Get its size
width, height = pil.size
# Modify img tag with image size
img['width'] = str(width) + "px"
img['height'] = str(height) + "px"
except KeyError:
pass
# Save the updated post
with open(fname, "wb") as file:
file.write(str(soup))
。
は、あなただけのクライアント側でこれを実行するためにJavaScriptを使用することができ、私もwrote a blog post about this issue
てきた、それがお役に立てば幸いです。あなたのためにはうまくいかない理由はありますか?私はあなたがなぜこれをやる必要があるのか聞いても好奇心が強いでしょう。 –
@KevinWorkman私はGoogle AMPページを実装しており、amp-imgは指定する属性を必要とするためです。 – elbaulp
@KevinWorkmanイメージタグは常にheight属性とwidth属性を持つ必要がありますが、表示するには必須ではありません。すべてのSEOツールは、欠落している場合、それらのフラグを立てます。 – Lee