LoginSignup
0
0

More than 3 years have passed since last update.

Python(Colab)でウェブ上の画像をドライブに保存する

Last updated at Posted at 2020-09-26

下記の写真をドライブに保存するコードです。

https://www.pakutaso.com/shared/img/thumb/nyannko458A3685_TP_V.jpg
nyannko458A3685_TP_V.jpg

前提としてColabで実行するコードで、
Pythonでやる場合はGCPでOAuthの設定が必要です。

ドライブの認証を通す

Colabでの認証
from google.colab import auth
auth.authenticate_user()

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from oauth2client.client import GoogleCredentials

gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)

画像を保存する

画像をjpegで保存
import requests
from io import BytesIO
from PIL import Image

url = 'https://www.pakutaso.com/shared/img/thumb/nyannko458A3685_TP_V.jpg'
file_name = 'ネコ.jpg'
FOLDER_ID = '' #保存したいフォルダIDを指定

r = requests.get(url)
i = Image.open(BytesIO(r.content))
i = i.resize(size=(200, 100)) #リサイズしたい場合に使用
i.save(file_name)

#IDを指定してUPLOADする
f = drive.CreateFile({'title' : file_name, 'parents':[{'id' : FOLDER_ID }]})
f.SetContentFile(file_name)
f.Upload()

別のセルでiを実行すると画像の確認が可能です。

jpeg以外で保存したい場合はファイル名の拡張子を変更したら変わります。
サポートされているフォーマット一覧は下記に載っています。
https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html

エラーが出た場合

ファイル名に拡張子を付け忘れると下記のエラーがでるので注意。

2020-09-26_11h03_41.png

PILでできること

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0