jpgでも、一度jpgに再変換してアップしたい。
理解しました。画像ファイルを一旦JPEG形式に再変換してアップロードする方法を説明します。
Pythonで画像ファイルを再変換してアップロードする手順は以下の通りです:
-
PILライブラリのインストール: 画像を処理するためにPython Imaging Library (PIL) またはそのフォークであるPillowを使用します。これにより、画像の読み込みと再変換が簡単に行えます。
bash
pip install Pillow -
画像の再変換とアップロード: 以下のステップで、画像を読み込み、JPEG形式に再変換し、それをWordPressにアップロードします。
python
from PIL import Image import requests # 画像をJPEG形式に再変換する関数 def convert_to_jpeg(original_image_path, output_image_path): try: with Image.open(original_image_path) as img: img.convert("RGB").save(output_image_path, "JPEG") return True except Exception as e: print(f"画像の再変換に失敗しました: {e}") return False # WordPressに画像をアップロードする関数 def upload_image_to_wordpress(image_path): try: url = 'https://your-wordpress-site.com/wp-json/wp/v2/media' headers = { 'Authorization': 'Bearer YOUR_ACCESS_TOKEN', # アクセストークンの設定が必要です 'Content-Disposition': 'attachment; filename=' + image_path.split('/')[-1] } with open(image_path, 'rb') as image_file: files = {'file': (image_path, image_file, 'image/jpeg')} response = requests.post(url, headers=headers, files=files) if response.status_code == 201: data = response.json() image_id = data['id'] image_url = data['source_url'] print(f"画像がアップロードされました。ID: {image_id}, URL: {image_url}") return image_id, image_url else: print(f"画像のアップロードに失敗しました。ステータスコード: {response.status_code}") print(response.text) return None, None except Exception as e: print(f"エラーが発生しました: {e}") return None, None # メイン処理 def main(original_image_path): output_image_path = original_image_path.replace('.svg', '.jpg') if convert_to_jpeg(original_image_path, output_image_path): image_id, image_url = upload_image_to_wordpress(output_image_path) if image_id: # ここで記事の作成や画像の追加などの後続処理を行う print("記事が作成されました。") else: print("画像のアップロードに失敗しました。") # 例としての実行 if __name__ == "__main__": image_path = r"C:UsersownerマイドライブPython scriptSakura landscape illustration_20240618_194017.jpg" main(image_path)
上記のコードでは、convert_to_jpeg関数でSVGやその他の形式の画像をJPEG形式に変換し、upload_image_to_wordpress関数で変換されたJPEG画像をWordPressにアップロードします。WordPressへのアップロードには、アクセストークンが必要であることに留意してください。また、main関数では指定した画像のパスを引数として渡して処理を開始します。
これにより、画像ファイルを再変換して、WordPressに正常にアップロードできるはずです。

ディスカッション
コメント一覧
まだ、コメントがありません