File indexing completed on 2024-04-28 08:50:23

0001 #! /usr/bin/env python
0002 import os
0003 import sys
0004 import exif
0005 
0006 def compose(delta, old):
0007   map=[0, 4, 2, 6, 5, 1, 7, 3]
0008   unmap=[1, 6, 3, 8, 2, 5, 4, 7]
0009   x = map[delta-1]
0010   y = map[old-1]
0011   z = ((x^y)&4) + ((y+(x&3)*(((y&4)>>1)+1))&3)
0012   return unmap[z]
0013 
0014 def deg2o(d):
0015   map={90:6, 270:8, 180:3}
0016   if map.has_key(d):
0017     return map[d]
0018   else:
0019     return 0
0020 
0021 if len(sys.argv) < 2:
0022   print 'Usage: %s [[+]orientnum] file\n' % sys.argv[0]
0023   sys.exit(1)
0024 try:
0025   if len(sys.argv) == 2:
0026     filename=sys.argv[1]
0027     file=open(filename, "r");
0028   else:
0029     filename=sys.argv[2]
0030     mod=sys.argv[1]
0031     fd = os.open(filename, os.O_RDWR)
0032     file=os.fdopen(fd,'r')
0033     # check file exists and is readable
0034     file.read(1)
0035     file.seek(0,0)
0036 except:
0037   print 'Cannot open', filename
0038   sys.exit(1)
0039 
0040 tags=exif.process_file(file,0,1)
0041 if not tags:
0042   print 'no EXIF information in', filename
0043   sys.exit(1)
0044 if not tags.has_key('Exif Offset') \
0045     or not tags.has_key('Image Orientation'):
0046   print 'cannot get orientation info in', filename
0047   sys.exit(1)
0048 
0049 exifp = tags['Exif Offset']
0050 endian = tags['Exif Endian']
0051 tagp = tags['Image Orientation'].field_offset
0052 
0053 orientp = exifp + tagp
0054 
0055 if endian == 'M': # MM byte order
0056   orientp += 1
0057 
0058 file.seek(orientp)
0059 o = ord(file.read(1))
0060 
0061 if o < 1 or o > 8:
0062   print 'orientation out of range', o
0063   sys.exit(1)
0064 
0065 if len(sys.argv) == 2:
0066   print 'orientation is', o
0067   sys.exit(0)
0068 
0069 try:
0070   if mod[0] == '+':
0071     deltao = int(mod)
0072     if 1 <= deltao and deltao <= 8:
0073       newo = compose(deltao, o)
0074     elif deg2o(deltao) != 0:
0075       newo = compose(deg2o(deltao), o)
0076     else:
0077       print 'cannot understand orientation modification', mod
0078       sys.exit(1) # it will still hit the except ... how to fix?
0079   else:
0080     newo = int(mod)
0081 except:
0082   print 'expected numeric orientation and got',mod
0083   sys.exit(1)
0084 
0085 if newo < 1 or newo > 8:
0086   newo = deg2o(newo)
0087   if newo == 0:
0088     print 'cannot understand orientation', deltao
0089     sys.exit(1)
0090 
0091 os.lseek(fd,orientp,0)
0092 os.write(fd,chr(newo))
0093 
0094 # Thumbnail orientation :
0095 thumb_ifdp = 0
0096 if tags.has_key('Thumbnail Orientation'):
0097   thumb_tagp = tags['Thumbnail Orientation'].field_offset
0098   thumb_orientp = exifp + thumb_tagp
0099   if endian == 'M': # MM byte order
0100     thumb_orientp += 1
0101   os.lseek(fd,thumb_orientp,0)
0102   os.write(fd,chr(newo))
0103 
0104 print 'orientation changed from', o, 'to', newo