栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用PIL调整大小和将旋转EXIF信息应用于文件?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用PIL调整大小和将旋转EXIF信息应用于文件?

我最终使用了pyexiv2,但是要在除GNU之外的其他平台上安装也有些棘手。

#!/usr/bin/python# -*- coding: utf-8 -*-# Copyright (C) 2008-2009 Rémy HUBSCHER <natim@users.sf.net> - http://www.trunat.fr/portfolio/python.html# This program is free software; you can redistribute it and/or modify# it under the terms of the GNU General Public License as published by# the Free Software Foundation; either version 2 of the License, or# (at your option) any later version.# This program is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the# GNU General Public License for more details.# You should have received a copy of the GNU General Public License along# with this program; if not, write to the Free Software Foundation, Inc.,# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.# Using :#   - Python Imaging Library PIL    http://www.pythonware.com/products/pil/index.htm#   - pyexiv2 http://tilloy.net/dev/pyexiv2/#### What is doing this script ?##  1. Take a directory of picture from a Reflex Camera (Nikon D90 for example)#  2. Use the EXIF Orientation information to turn the image#  3. Remove the thumbnail from the EXIF Information#  4. Create 2 image one maxi map in 600x600, one mini map in 200x200#  5. Add a comment with the name of the Author and his Website#  6. Copy the EXIF information to the maxi and mini image#  7. Name the image files with a meanful name (Date of picture)import os, systry:    import Imageexcept:    print "To use this program, you need to install Python Imaging Library - http://www.pythonware.com/products/pil/"    sys.exit(1)try:    import pyexiv2except:    print "To use this program, you need to install pyexiv2 - http://tilloy.net/dev/pyexiv2/"    sys.exit(1)############# Configuration ##############size_mini = 200, 200size_maxi = 1024, 1024# Information about the Photograph should be in ASCIICOPYRIGHT="Remy Hubscher - http://www.trunat.fr/"ARTIST="Remy Hubscher"##########################################def listJPEG(directory):    "Retourn a list of the JPEG files in the directory"    fileList = [os.path.normcase(f) for f in os.listdir(directory)]    fileList = [f for f in fileList if os.path.splitext(f)[1]  in ('.jpg', '.JPG')]    fileList.sort()    return fileListdef _mkdir(newdir):    """    works the way a good mkdir should :)      - already exists, silently complete      - regular file in the way, raise an exception      - parent directory(ies) does not exist, make them as well    """    if os.path.isdir(newdir):        pass    elif os.path.isfile(newdir):        raise OSError("a file with the same name as the desired " "dir, '%s', already exists." % newdir)    else:        head, tail = os.path.split(newdir)        if head and not os.path.isdir(head): _mkdir(head)        if tail: os.mkdir(newdir)if len(sys.argv) < 3:    print "USAGE : python %s indir outdir [comment]" % sys.argv[0]    exitindir  = sys.argv[1]outdir = sys.argv[2]if len(sys.argv) == 4:    comment = sys.argv[1]else:    comment = COPYRIGHTagrandie = os.path.join(outdir, 'agrandie')miniature = os.path.join(outdir, 'miniature')print agrandie, miniature_mkdir(agrandie)_mkdir(miniature)for infile in listJPEG(indir):    mini  = os.path.join(miniature, infile)    grand = os.path.join(agrandie, infile)    file_path = os.path.join(indir, infile)    image = pyexiv2.Image(file_path)    image.readmetadata()    # We clean the file and add some information    image.deleteThumbnail()    image['Exif.Image.Artist'] = ARTIST    image['Exif.Image.Copyright'] = COPYRIGHT    image.setComment(comment)    # I prefer not to modify the input file    # image.writemetadata()    # We look for a meanful name    if 'Exif.Image.DateTime' in image.exifKeys():        filename = image['Exif.Image.DateTime'].strftime('%Y-%m-%d_%H-%M-%S.jpg')        mini  = os.path.join(miniature, filename)        grand = os.path.join(agrandie, filename)    else:        # If no exif information, leave the old name        mini  = os.path.join(miniature, infile)        grand = os.path.join(agrandie, infile)    # We create the thumbnail    #try:    im = Image.open(file_path)    im.thumbnail(size_maxi, Image.ANTIALIAS)    # We rotate regarding to the EXIF orientation information    if 'Exif.Image.Orientation' in image.exifKeys():        orientation = image['Exif.Image.Orientation']        if orientation == 1: # Nothing mirror = im.copy()        elif orientation == 2: # Vertical Mirror mirror = im.transpose(Image.FLIP_LEFT_RIGHT)        elif orientation == 3: # Rotation 180° mirror = im.transpose(Image.ROTATE_180)        elif orientation == 4: # Horizontal Mirror mirror = im.transpose(Image.FLIP_TOP_BOTTOM)        elif orientation == 5: # Horizontal Mirror + Rotation 90° CCW mirror = im.transpose(Image.FLIP_TOP_BOTTOM).transpose(Image.ROTATE_90)        elif orientation == 6: # Rotation 270° mirror = im.transpose(Image.ROTATE_270)        elif orientation == 7: # Horizontal Mirror + Rotation 270° mirror = im.transpose(Image.FLIP_TOP_BOTTOM).transpose(Image.ROTATE_270)        elif orientation == 8: # Rotation 90° mirror = im.transpose(Image.ROTATE_90)        # No more Orientation information        image['Exif.Image.Orientation'] = 1    else:        # No EXIF information, the user has to do it        mirror = im.copy()    mirror.save(grand, "JPEG", quality=85)    img_grand = pyexiv2.Image(grand)    img_grand.readmetadata()    image.copymetadataTo(img_grand)    img_grand.writemetadata()    print grand    mirror.thumbnail(size_mini, Image.ANTIALIAS)    mirror.save(mini, "JPEG", quality=85)    img_mini = pyexiv2.Image(mini)    img_mini.readmetadata()    image.copymetadataTo(img_mini)    img_mini.writemetadata()    print mini    print

如果您发现可以改进的地方(除了仍然适用于Python 2.5,请告诉我)。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/639851.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号