2017年7月18日 星期二

Python - How to Include image in jupyter notebook? How to download image from url? - 在Jupyter上顯示本地端與網路上圖片、下載圖片到本地端

Version:

Python version:Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version:Windows 10

方法一

Code:

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

def mkdir(path):
    import os
    if  os.path.exists(path) == False:
        os.makedirs(path)
        print('mkdir:',path)
    elif  os.path.exists(path) == True:
        print('dir already exist:',path)

dir_path = './image/'
file_anme = 'google.jpg'
pic_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/1200px-Google_2015_logo.svg.png"
mkdir(dir_path)

# 下載圖片 download image
import requests
with open(dir_path + file_anme, 'wb') as handle:
        response = requests.get(pic_url, stream=True)
        if not response.ok:
            print (response)
        for block in response.iter_content(1024):
            if not block:
                break
            handle.write(block)

# 顯示網路圖片
from IPython.display import Image
from IPython.core.display import HTML 
# 顯示網路圖片(from url)
Image(url= pic_url)
# 顯示本地圖片(from local filesystem)
Image(url= dir_path + file_anme)

方法二

<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/1200px-Google_2015_logo.svg.png">

Result:

沒有留言:

張貼留言