LoginSignup
0
0

JupyterNotebookに画像を埋め込むのに便利なの作った

Last updated at Posted at 2023-11-04

使い方

  1. 画像をクリップボードにコピー。Windows + Shift + S でスクショ等
  2. 下記関数を読んでpic2html()を実行。クリップボードの画像がhtmlに変換されクリップボードに戻される
  3. Markdown形式のセルに貼り付けてEnter

必要ライブラリ

pip install pillow
pip install pyperclip

注意点

クリップボードを読み込む都合上ローカルのJupyterでしか動かないです。リモートのJupyterやColab等では使えません。
macOSとWindowsでは動作確認済みです

コード

import base64
import io
from PIL import ImageGrab
import pyperclip

def pic2html():

    im = ImageGrab.grabclipboard()
    if not im:
        print("画像をコピーしてから実行してください")
        return

    w, h = im.size
    max_width = 970
    max_height = 500
    nw = min(w, max_width)    
    nh = int(h * (nw / w))
    if nh > max_height:
        nh = min(h, max_height)
        nw = int(w * (nh / h))

    im = im.resize((nw,nh))
    buf = io.BytesIO()
    im.save(buf, "webp")
    data = base64.b64encode(buf.getvalue()).decode('utf-8')
    html = '<img src="data:image/png;base64,{}" style="border:solid 1px #000000" width="{}" height="{}">'.format(
        data, im.width - 2, im.height - 2
    )
    try:
        pyperclip.copy(html)
        print("クリップボードにコピーされました")
    except Exception as e:
        print("クリップボードへのコピーに失敗しました:", str(e))

いきさつ

JupyterNotebookで集計を詳しく説明する際にExcelの資料をコピペで貼り付けたかった。

  1. 画像を外部ファイルとして参照するようにするのが普通だが、ノートをどこに持って行っても表示できるようにしておきたかった。ファイルをどこかにアップしてURLを参照するやり方は面倒でやりたくなかった。
  2. Base64で埋め込む方法が良いのだが、画像サイズを小さくしないと文字数が増えすぎるので変換ツールを作ることにした。高圧縮のwebp形式で解像度をノートブックで表示するのにちょうどいい感じにする
  3. 画像の読み込みのために、ファイルのパスを指定するのは面倒なのでクリップボードを使うことにした
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