LoginSignup
8
7

More than 5 years have passed since last update.

Pythonとhtmlで写真を表示

Last updated at Posted at 2017-01-18

概要

私は Macbook pro 13inch retina を使っており, iPad やデジカメで撮った写真の管理は,Mac付属の「写真アプリ」で行っている.
でも,ガールフレンドの写真など,あるグループの写真のみを別のフォルダに集めて管理したり眺めたりしたいというニーズから,あるフォルダにコピーした JPG イメージを,html でサムネイルのように表示させるプログラムを作ってみた.実際にサムネイルは作成しておらず,html 上で,小さく表示させているだけである.

元の画像はそのままで,観賞用に明るさの補正を行ったものを別に保存・管理する場合などにも使える.ちなみに,以下はImageMagickのコマンドで,暗い写真を明るく画像補正するコマンド.数値が大きい方が,明るくなる.

convert IMG_0461.JPG  -sigmoidal-contrast 10,0%  IMG_0461.jpg
convert IMG_0494.JPG  -sigmoidal-contrast  7,0%  IMG_0494.jpg
convert IMG_0333.JPG  -sigmoidal-contrast  4,0%  IMG_0333.jpg

プログラミングの考え方

  • Pythonプログラムは表示したい写真と同じフォルダに入っている
  • html の table タグで写真を並べて表示する
  • 写真は,横5列,縦は必要な段数としている
  • JPG拡張子のみのファイルを選び出し,ファイル名を取得し,img srcでイメージを表示する
  • 原写真には縦長,横長双方が含まれるが,幅を200pxに統一して表示させる
  • 写真の下にファイル名を表示し,これをクリックすると原写真が見られる

ソースコード

py_pic.py
import os
from PIL import Image

filenames = os.listdir('./')
imgl=[]
ww=[]
hh=[]
for fname in sorted(filenames):
    path, ext = os.path.splitext( os.path.basename(fname) )
    if ext=='.JPG' and path[0:2]!='._':
        pic=path+ext
        im=Image.open(pic)
        w=im.size[0]
        h=im.size[1]
        print(pic, w, h)
        imgl=imgl+[pic]
        ww=ww+[w]
        hh=hh+[h]

f=open('maggie.html','w')
print('<html>',file=f)
print('<body>',file=f)
print('<table>',file=f)
n=len(imgl)
m=int(n/5)+1
k=-1
for i in range(0,m):
    print('<tr>',file=f)
    for j in range(0,5):
        k=k+1
        if k<=n-1:
            pic=imgl[k]
            w1=200
            h1=int(hh[k]/ww[k]*200)
            print('<td align="center"><img src="'+pic+'" alt="pic" width="'+str(w1)+'", height="'+str(h1)+'"><br><a href="'+pic+'">I'+pic+'<a></td>',file=f)
        else:
            print('<td></td>',file=f)
    print('</tr>',file=f)
print('</table>',file=f)
print('</body>',file=f)
print('</html>',file=f)
f.close()

以 上

8
7
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
8
7