를 사용하는 방법 PIL 크기를 조정하고 회전 적용 EXIF information file?
-
05-07-2019 - |
문제
하게 사용할 수 있는 파이썬 크기를 조정하는 사진입니다.내 카메라,파일은 모든 서면입니다 풍경의 방법입니다.
Exif 정보를 처리하는 태그를 물 이미지 뷰어에서 회전하는 방법이다.대부분의 브라우저를 이해하지 못하는 이 정보를 나는 원하는 이미지를 회전하는 이를 사용하 EXIF 정보를 유지하는 모든 다른 EXIF information.
어떻게 할 수 있는 것을 사용하는 파이썬?
읽기 EXIF.py 소스 코드,내가 찾은 뭔가 다음과 같다:
0x0112: ('Orientation',
{1: 'Horizontal (normal)',
2: 'Mirrored horizontal',
3: 'Rotated 180',
4: 'Mirrored vertical',
5: 'Mirrored horizontal then rotated 90 CCW',
6: 'Rotated 90 CW',
7: 'Mirrored horizontal then rotated 90 CW',
8: 'Rotated 90 CCW'})
할 수 있는 방법 이 정보를 사용하고 필을 적용합니까?
해결책
마지막으로 사용되는 pyexiv2, 지만,그것은 까다로운 설치하는 다른 플랫폼에서 보다는 것입니다.
#!/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, sys
try:
import Image
except:
print "To use this program, you need to install Python Imaging Library - http://www.pythonware.com/products/pil/"
sys.exit(1)
try:
import pyexiv2
except:
print "To use this program, you need to install pyexiv2 - http://tilloy.net/dev/pyexiv2/"
sys.exit(1)
############# Configuration ##############
size_mini = 200, 200
size_maxi = 1024, 1024
# Information about the Photograph should be in ASCII
COPYRIGHT="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 fileList
def _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]
exit
indir = sys.argv[1]
outdir = sys.argv[2]
if len(sys.argv) == 4:
comment = sys.argv[1]
else:
comment = COPYRIGHT
agrandie = 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
당신이 볼 무언가가 될 수 있는 개선(제외한다는 사실은 아직도에 대한 Python2.5)다음을 알려주시기 바랍니다.
다른 팁
지만 PIL 읽을 수 있습 EXIF 메타데이터,그렇지 않을 변경할 수있는 능력을 가지고 그것을 쓰고 그것을 다시는 이미지 파일입니다.
더 나은 선택입니다 pyexiv2 라이브러리입니다.이 라이브러리와 그것은 아주 간단한 플립 사진 방향입니다.예를 들어 다음과 같습니다.
import sys
import pyexiv2
image = pyexiv2.Image(sys.argv[1])
image.readMetadata()
image['Exif.Image.Orientation'] = 6
image.writeMetadata()
이 방향을 설정합 6 에 해당하는"90CW".
첫째로 당신은 당신이 있는지 확인하는 카메라는 실제로 회전 센서입니다.대부분의 카메라 모델에서 단순히 방향을 설정하는 태그를 1(수평)에 대한 모든 그림이다.
그때 사용하는 것이 좋습니다 pyexiv2 및 pyjpegtran 의 경우입니다.PIL 지원하지 않는 무손실 회전,는 도메인의 pyjpegtran.pyexiv2 은 라이브러리 복사할 수 있는 메타데이터 중 하나에서 다른 이미지(나는 생각한 메서드 이름이 copyMetadata).
당신은 당신을 원하지 않는 크기를 조정하는 사진을 표시하기 전에 브라우저에서?8 메가 픽셀 JPEG 는 너무 큰 브라우저 창고는 원인이 될 것이 끝없이 로딩 시간.