エラーが発生しました: ‘latin-1’ codec can’t encode characters in position 36-41: ordinal not in range(256) 画像のアップロードに失敗しました。
エラー 'latin-1' codec can't encode characters in position 36-41: ordinal not in range(256) は、日本語のファイルパスやファイル名に関連するエンコーディングの問題が原因で発生しています。この問題を解決するために、ファイルパスやファイル名の文字列を適切にエンコードする必要があります。
具体的には、ファイルパスを扱う際に、以下のような手順を考慮する必要があります:
-
ファイルパスのエンコーディング: ファイルシステムやHTTPリクエストで扱う日本語文字列を、正しいエンコーディングで処理します。通常、UTF-8が推奨されますが、システムや使用するライブラリによって異なることがあります。
-
ファイル名の取得: ファイルパスからファイル名部分を取得する際、エンコーディングを意識して取得します。Pythonの標準ライブラリである
os.path.basename()を使用すると、ファイル名の取得が簡単です。 -
ファイルの読み込みと変換: PILライブラリやその他の画像処理ライブラリで画像を読み込む際、ファイルパスやファイル名が適切にエンコードされていることを確認します。
以下に、これらのポイントを考慮した修正例を示します:
python
from PIL import Image
import requests
import os
# 画像を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': f'attachment; filename="{os.path.basename(image_path)}"'
}
with open(image_path, 'rb') as image_file:
files = {'file': (os.path.basename(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)
上記の修正例では、Content-Dispositionヘッダーを正しく設定し、ファイル名をos.path.basename()関数を使用して取得しています。これにより、ファイル名のエンコーディングに関する問題を回避し、画像の再変換とアップロードが正常に行われることを期待します。
ファイルパスやファイル名に関するエンコーディングの問題が解決されれば、再度アップロードを試みてください。

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