鱼C论坛

 找回密码
 立即注册
12
返回列表 发新帖
楼主: jerryxjr1220

[技术交流] python图像处理库pillow使用说明

[复制链接]
 楼主| 发表于 2016-11-8 15:08:53 | 显示全部楼层
The ImageTk module contains support to create and modify Tkinter BitmapImage and PhotoImage objects from PIL images.

For examples, see the demo programs in the Scripts directory.

class PIL.ImageTk.BitmapImage(image=None, **kw)
A Tkinter-compatible bitmap image. This can be used everywhere Tkinter expects an image object.

The given image must have mode “1”. Pixels having value 0 are treated as transparent. Options, if any, are passed on to Tkinter. The most commonly used option is foreground, which is used to specify the color for the non-transparent parts. See the Tkinter documentation for information on how to specify colours.

Parameters:        image – A PIL image.
height()
Get the height of the image.

Returns:        The height, in pixels.
width()
Get the width of the image.

Returns:        The width, in pixels.
class PIL.ImageTk.PhotoImage(image=None, size=None, **kw)
A Tkinter-compatible photo image. This can be used everywhere Tkinter expects an image object. If the image is an RGBA image, pixels having alpha 0 are treated as transparent.

The constructor takes either a PIL image, or a mode and a size. Alternatively, you can use the file or data options to initialize the photo image object.

Parameters:       
image – Either a PIL image, or a mode string. If a mode string is used, a size must also be given.
size – If the first argument is a mode string, this defines the size of the image.
file – A filename to load the image from (using Image.open(file)).
data – An 8-bit string containing image data (as loaded from an image file).
height()
Get the height of the image.

Returns:        The height, in pixels.
paste(im, box=None)
Paste a PIL image into the photo image. Note that this can be very slow if the photo image is displayed.

Parameters:       
im – A PIL image. The size must match the target region. If the mode does not match, the image is converted to the mode of the bitmap image.
box – A 4-tuple defining the left, upper, right, and lower pixel coordinate. If None is given instead of a tuple, all of the image is assumed.
width()
Get the width of the image.

Returns:        The width, in pixels.
Next  Previous
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 15:10:17 | 显示全部楼层
ImageWin Module (Windows-only)
The ImageWin module contains support to create and display images on Windows.

ImageWin can be used with PythonWin and other user interface toolkits that provide access to Windows device contexts or window handles. For example, Tkinter makes the window handle available via the winfo_id method:

from PIL import ImageWin

dib = ImageWin.Dib(...)

hwnd = ImageWin.HWND(widget.winfo_id())
dib.draw(hwnd, xy)
class PIL.ImageWin.Dib(image, size=None)
A Windows bitmap with the given mode and size. The mode can be one of “1”, “L”, “P”, or “RGB”.

If the display requires a palette, this constructor creates a suitable palette and associates it with the image. For an “L” image, 128 greylevels are allocated. For an “RGB” image, a 6x6x6 colour cube is used, together with 20 greylevels.

To make sure that palettes work properly under Windows, you must call the palette method upon certain events from Windows.

Parameters:       
image – Either a PIL image, or a mode string. If a mode string is used, a size must also be given. The mode can be one of “1”, “L”, “P”, or “RGB”.
size – If the first argument is a mode string, this defines the size of the image.
draw(handle, dst, src=None)
Same as expose, but allows you to specify where to draw the image, and what part of it to draw.

The destination and source areas are given as 4-tuple rectangles. If the source is omitted, the entire image is copied. If the source and the destination have different sizes, the image is resized as necessary.

expose(handle)
Copy the bitmap contents to a device context.

Parameters:        handle – Device context (HDC), cast to a Python integer, or an HDC or HWND instance. In PythonWin, you can use the CDC.GetHandleAttrib() to get a suitable handle.
frombytes(buffer)
Load display memory contents from byte data.

Parameters:        buffer – A buffer containing display data (usually data returned from <b>tobytes</b>)
paste(im, box=None)
Paste a PIL image into the bitmap image.

Parameters:       
im – A PIL image. The size must match the target region. If the mode does not match, the image is converted to the mode of the bitmap image.
box – A 4-tuple defining the left, upper, right, and lower pixel coordinate. If None is given instead of a tuple, all of the image is assumed.
query_palette(handle)
Installs the palette associated with the image in the given device context.

This method should be called upon QUERYNEWPALETTE and PALETTECHANGED events from Windows. If this method returns a non-zero value, one or more display palette entries were changed, and the image should be redrawn.

Parameters:        handle – Device context (HDC), cast to a Python integer, or an HDC or HWND instance.
Returns:        A true value if one or more entries were changed (this indicates that the image should be redrawn).
tobytes()
Copy display memory contents to bytes object.

Returns:        A bytes object containing display data.
class PIL.ImageWin.HDC(dc)
Wraps an HDC integer. The resulting object can be passed to the draw() and expose() methods.

class PIL.ImageWin.HWND(wnd)
Wraps an HWND integer. The resulting object can be passed to the draw() and expose() methods, instead of a DC.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 15:11:07 | 显示全部楼层
ExifTags Module
The ExifTags module exposes two dictionaries which provide constants and clear-text names for various well-known EXIF tags.

class PIL.ExifTags.TAGS
The TAG dictionary maps 16-bit integer EXIF tag enumerations to descriptive string names. For instance:

>>> from PIL.ExifTags import TAGS
>>> TAGS[0x010e]
'ImageDescription'
class PIL.ExifTags.GPSTAGS
The GPSTAGS dictionary maps 8-bit integer EXIF gps enumerations to descriptive string names. For instance:

>>> from PIL.ExifTags import GPSTAGS
>>> GPSTAGS[20]
'GPSDestLatitude'
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 15:14:00 | 显示全部楼层
OleFileIO Module
The OleFileIO module reads Microsoft OLE2 files (also called Structured Storage or Microsoft Compound Document File Format), such as Microsoft Office documents, Image Composer and FlashPix files, and Outlook messages.

This module is the OleFileIO_PL project by Philippe Lagadec, v0.42, merged back into Pillow.

How to use this module
For more information, see also the file PIL/OleFileIO.py, sample code at the end of the module itself, and docstrings within the code.

About the structure of OLE files
An OLE file can be seen as a mini file system or a Zip archive: It contains streams of data that look like files embedded within the OLE file. Each stream has a name. For example, the main stream of a MS Word document containing its text is named “WordDocument”.

An OLE file can also contain storages. A storage is a folder that contains streams or other storages. For example, a MS Word document with VBA macros has a storage called “Macros”.

Special streams can contain properties. A property is a specific value that can be used to store information such as the metadata of a document (title, author, creation date, etc). Property stream names usually start with the character ‘05’.

For example, a typical MS Word document may look like this:

\x05DocumentSummaryInformation (stream)
\x05SummaryInformation (stream)
WordDocument (stream)
Macros (storage)
    PROJECT (stream)
    PROJECTwm (stream)
    VBA (storage)
        Module1 (stream)
        ThisDocument (stream)
        _VBA_PROJECT (stream)
        dir (stream)
ObjectPool (storage)
Test if a file is an OLE container
Use isOleFile to check if the first bytes of the file contain the Magic for OLE files, before opening it. isOleFile returns True if it is an OLE file, False otherwise.

assert OleFileIO.isOleFile('myfile.doc')
Open an OLE file from disk
Create an OleFileIO object with the file path as parameter:

ole = OleFileIO.OleFileIO('myfile.doc')
Open an OLE file from a file-like object
This is useful if the file is not on disk, e.g. already stored in a string or as a file-like object.

ole = OleFileIO.OleFileIO(f)
For example the code below reads a file into a string, then uses BytesIO to turn it into a file-like object.

data = open('myfile.doc', 'rb').read()
f = io.BytesIO(data) # or StringIO.StringIO for Python 2.x
ole = OleFileIO.OleFileIO(f)
How to handle malformed OLE files
By default, the parser is configured to be as robust and permissive as possible, allowing to parse most malformed OLE files. Only fatal errors will raise an exception. It is possible to tell the parser to be more strict in order to raise exceptions for files that do not fully conform to the OLE specifications, using the raise_defect option:

ole = OleFileIO.OleFileIO('myfile.doc', raise_defects=DEFECT_INCORRECT)
When the parsing is done, the list of non-fatal issues detected is available as a list in the parsing_issues attribute of the OleFileIO object:

print('Non-fatal issues raised during parsing:')
if ole.parsing_issues:
    for exctype, msg in ole.parsing_issues:
        print('- %s: %s' % (exctype.__name__, msg))
else:
    print('None')
Syntax for stream and storage path
Two different syntaxes are allowed for methods that need or return the path of streams and storages:

Either a list of strings including all the storages from the root up to the stream/storage name. For example a stream called “WordDocument” at the root will have [‘WordDocument’] as full path. A stream called “ThisDocument” located in the storage “Macros/VBA” will be [‘Macros’, ‘VBA’, ‘ThisDocument’]. This is the original syntax from PIL. While hard to read and not very convenient, this syntax works in all cases.
Or a single string with slashes to separate storage and stream names (similar to the Unix path syntax). The previous examples would be ‘WordDocument’ and ‘Macros/VBA/ThisDocument’. This syntax is easier, but may fail if a stream or storage name contains a slash.
Both are case-insensitive.

Switching between the two is easy:

slash_path = '/'.join(list_path)
list_path  = slash_path.split('/')
Get the list of streams
listdir() returns a list of all the streams contained in the OLE file, including those stored in storages. Each stream is listed itself as a list, as described above.

print(ole.listdir())
Sample result:

[['\x01CompObj'], ['\x05DocumentSummaryInformation'], ['\x05SummaryInformation']
, ['1Table'], ['Macros', 'PROJECT'], ['Macros', 'PROJECTwm'], ['Macros', 'VBA',
'Module1'], ['Macros', 'VBA', 'ThisDocument'], ['Macros', 'VBA', '_VBA_PROJECT']
, ['Macros', 'VBA', 'dir'], ['ObjectPool'], ['WordDocument']]
As an option it is possible to choose if storages should also be listed, with or without streams:

ole.listdir (streams=False, storages=True)
Test if known streams/storages exist:
exists(path) checks if a given stream or storage exists in the OLE file.

if ole.exists('worddocument'):
    print("This is a Word document.")
    if ole.exists('macros/vba'):
         print("This document seems to contain VBA macros.")
Read data from a stream
openstream(path) opens a stream as a file-like object.

The following example extracts the “Pictures” stream from a PPT file:

pics = ole.openstream('Pictures')
data = pics.read()
Get information about a stream/storage
Several methods can provide the size, type and timestamps of a given stream/storage:

get_size(path) returns the size of a stream in bytes:

s = ole.get_size('WordDocument')
get_type(path) returns the type of a stream/storage, as one of the following constants: STGTY_STREAM for a stream, STGTY_STORAGE for a storage, STGTY_ROOT for the root entry, and False for a non existing path.

t = ole.get_type('WordDocument')
get_ctime(path) and get_mtime(path) return the creation and modification timestamps of a stream/storage, as a Python datetime object with UTC timezone. Please note that these timestamps are only present if the application that created the OLE file explicitly stored them, which is rarely the case. When not present, these methods return None.

c = ole.get_ctime('WordDocument')
m = ole.get_mtime('WordDocument')
The root storage is a special case: You can get its creation and modification timestamps using the OleFileIO.root attribute:

c = ole.root.getctime()
m = ole.root.getmtime()
Extract metadata
get_metadata() will check if standard property streams exist, parse all the properties they contain, and return an OleMetadata object with the found properties as attributes.

meta = ole.get_metadata()
print('Author:', meta.author)
print('Title:', meta.title)
print('Creation date:', meta.create_time)
# print all metadata:
meta.dump()
Available attributes include:

codepage, title, subject, author, keywords, comments, template,
last_saved_by, revision_number, total_edit_time, last_printed, create_time,
last_saved_time, num_pages, num_words, num_chars, thumbnail,
creating_application, security, codepage_doc, category, presentation_target,
bytes, lines, paragraphs, slides, notes, hidden_slides, mm_clips,
scale_crop, heading_pairs, titles_of_parts, manager, company, links_dirty,
chars_with_spaces, unused, shared_doc, link_base, hlinks, hlinks_changed,
version, dig_sig, content_type, content_status, language, doc_version
See the source code of the OleMetadata class for more information.

Parse a property stream
get_properties(path) can be used to parse any property stream that is not handled by get_metadata. It returns a dictionary indexed by integers. Each integer is the index of the property, pointing to its value. For example in the standard property stream ‘05SummaryInformation’, the document title is property #2, and the subject is #3.

p = ole.getproperties('specialprops')
By default as in the original PIL version, timestamp properties are converted into a number of seconds since Jan 1,1601. With the option convert_time, you can obtain more convenient Python datetime objects (UTC timezone). If some time properties should not be converted (such as total editing time in ‘05SummaryInformation’), the list of indexes can be passed as no_conversion:

p = ole.getproperties('specialprops', convert_time=True, no_conversion=[10])
Close the OLE file
Unless your application is a simple script that terminates after processing an OLE file, do not forget to close each OleFileIO object after parsing to close the file on disk.

ole.close()
Use OleFileIO as a script
OleFileIO can also be used as a script from the command-line to display the structure of an OLE file and its metadata, for example:

PIL/OleFileIO.py myfile.doc
You can use the option -c to check that all streams can be read fully, and -d to generate very verbose debugging information.

How to contribute
The code is available in a Mercurial repository on bitbucket. You may use it to submit enhancements or to report any issue.

If you would like to help us improve this module, or simply provide feedback, please contact me. You can help in many ways:

test this module on different platforms / Python versions
find and report bugs
improve documentation, code samples, docstrings
write unittest test cases
provide tricky malformed files
How to report bugs
To report a bug, for example a normal file which is not parsed correctly, please use the issue reporting page, or if you prefer to do it privately, use this contact form. Please provide all the information about the context and how to reproduce the bug.

If possible please join the debugging output of OleFileIO. For this, launch the following command :

PIL/OleFileIO.py -d -c file >debug.txt
Classes and Methods
class PIL.OleFileIO.OleFileIO(filename=None, raise_defects=40, write_mode=False, debug=False, path_encoding='utf-8')
Bases: object

OLE container object

This class encapsulates the interface to an OLE 2 structured storage file. Use the listdir() and openstream() methods to access the contents of this file.

Object names are given as a list of strings, one for each subentry level. The root entry should be omitted. For example, the following code extracts all image streams from a Microsoft Image Composer file:

ole = OleFileIO("fan.mic")

for entry in ole.listdir():
    if entry[1:2] == "Image":
        fin = ole.openstream(entry)
        fout = open(entry[0:1], "wb")
        while True:
            s = fin.read(8192)
            if not s:
                break
            fout.write(s)
You can use the viewer application provided with the Python Imaging Library to view the resulting files (which happens to be standard TIFF files).

close()
close the OLE file, to release the file object

dumpdirectory()
Dump directory (for debugging only)

dumpfat(fat, firstindex=0)
Displays a part of FAT in human-readable form for debugging purpose

dumpsect(sector, firstindex=0)
Displays a sector in a human-readable form, for debugging purpose.

exists(filename)
Test if given filename exists as a stream or a storage in the OLE container. Note: filename is case-insensitive.

Parameters:        filename – path of stream in storage tree. (see openstream for syntax)
Returns:        True if object exist, else False.
get_metadata()
Parse standard properties streams, return an OleMetadata object containing all the available metadata. (also stored in the metadata attribute of the OleFileIO object)

new in version 0.25

get_rootentry_name()
Return root entry name. Should usually be ‘Root Entry’ or ‘R’ in most implementations.

get_size(filename)
Return size of a stream in the OLE container, in bytes.

Parameters:       
filename – path of stream in storage tree (see openstream for syntax)

Returns:       
size in bytes (long integer)

Raises:       
IOError – if file not found
TypeError – if this is not a stream.
get_type(filename)
Test if given filename exists as a stream or a storage in the OLE container, and return its type.

Parameters:        filename – path of stream in storage tree. (see openstream for syntax)
Returns:        False if object does not exist, its entry type (>0) otherwise:
STGTY_STREAM: a stream
STGTY_STORAGE: a storage
STGTY_ROOT: the root entry
getctime(filename)
Return creation time of a stream/storage.

Parameters:        filename – path of stream/storage in storage tree. (see openstream for syntax)
Returns:        None if creation time is null, a python datetime object otherwise (UTC timezone)
new in version 0.26

getmtime(filename)
Return modification time of a stream/storage.

Parameters:        filename – path of stream/storage in storage tree. (see openstream for syntax)
Returns:        None if modification time is null, a python datetime object otherwise (UTC timezone)
new in version 0.26

getproperties(filename, convert_time=False, no_conversion=None)
Return properties described in substream.

Parameters:       
filename – path of stream in storage tree (see openstream for syntax)
convert_time – bool, if True timestamps will be converted to Python datetime
no_conversion – None or list of int, timestamps not to be converted (for example total editing time is not a real timestamp)
Returns:       
a dictionary of values indexed by id (integer)

getsect(sect)
Read given sector from file on disk.

Parameters:        sect – int, sector index
Returns:        a string containing the sector data.
listdir(streams=True, storages=False)
Return a list of streams and/or storages stored in this file

Parameters:       
streams – bool, include streams if True (True by default) - new in v0.26
storages – bool, include storages if True (False by default) - new in v0.26 (note: the root storage is never included)
Returns:       
list of stream and/or storage paths

loaddirectory(sect)
Load the directory.

Parameters:        sect – sector index of directory stream.
loadfat(header)
Load the FAT table.

loadfat_sect(sect)
Adds the indexes of the given sector to the FAT

Parameters:        sect – string containing the first FAT sector, or array of long integers
Returns:        index of last FAT sector.
loadminifat()
Load the MiniFAT table.

open(filename, write_mode=False)
Open an OLE2 file in read-only or read/write mode. Read and parse the header, FAT and directory.

Parameters:       
filename –
string-like or file-like object, OLE file to parse

if filename is a string smaller than 1536 bytes, it is the path of the file to open. (bytes or unicode string)
if filename is a string longer than 1535 bytes, it is parsed as the content of an OLE file in memory. (bytes type only)
if filename is a file-like object (with read, seek and tell methods), it is parsed as-is.
write_mode – bool, if True the file is opened in read/write mode instead of read-only by default. (ignored if filename is not a path)
openstream(filename)
Open a stream as a read-only file object (BytesIO). Note: filename is case-insensitive.

Parameters:        filename –
path of stream in storage tree (except root entry), either:

a string using Unix path syntax, for example: ‘storage_1/storage_1.2/stream’
or a list of storage filenames, path to the desired stream/storage. Example: [‘storage_1’, ‘storage_1.2’, ‘stream’]
Returns:        file object (read-only)
Raises:        IOError – if filename not found, or if this is not a stream.
raise_defect(defect_level, message, exception_type=<type 'exceptions.IOError'>)
This method should be called for any defect found during file parsing. It may raise an IOError exception according to the minimal level chosen for the OleFileIO object.

Parameters:       
defect_level –
defect level, possible values are:

DEFECT_UNSURE : a case which looks weird, but not sure it’s a defect
DEFECT_POTENTIAL : a potential defect
DEFECT_INCORRECT : an error according to specifications, but parsing can go on
DEFECT_FATAL : an error which cannot be ignored, parsing is impossible
message – string describing the defect, used with raised exception.
exception_type – exception class to be raised, IOError by default
sect2array(sect)
convert a sector to an array of 32 bits unsigned integers, swapping bytes on big endian CPUs such as PowerPC (old Macs)

write_sect(sect, data, padding='\x00')
Write given sector to file on disk.

Parameters:       
sect – int, sector index
data – bytes, sector data
padding – single byte, padding character if data < sector size
write_stream(stream_name, data)
Write a stream to disk. For now, it is only possible to replace an existing stream by data of the same size.

Parameters:       
stream_name –
path of stream in storage tree (except root entry), either:

a string using Unix path syntax, for example: ‘storage_1/storage_1.2/stream’
or a list of storage filenames, path to the desired stream/storage. Example: [‘storage_1’, ‘storage_1.2’, ‘stream’]
data – bytes, data to be written, must be the same size as the original stream.
class PIL.OleFileIO.OleMetadata
Bases: object

class to parse and store metadata from standard properties of OLE files.

Available attributes: codepage, title, subject, author, keywords, comments, template, last_saved_by, revision_number, total_edit_time, last_printed, create_time, last_saved_time, num_pages, num_words, num_chars, thumbnail, creating_application, security, codepage_doc, category, presentation_target, bytes, lines, paragraphs, slides, notes, hidden_slides, mm_clips, scale_crop, heading_pairs, titles_of_parts, manager, company, links_dirty, chars_with_spaces, unused, shared_doc, link_base, hlinks, hlinks_changed, version, dig_sig, content_type, content_status, language, doc_version

Note: an attribute is set to None when not present in the properties of the OLE file.

References for SummaryInformation stream: - http://msdn.microsoft.com/en-us/library/dd942545.aspx - http://msdn.microsoft.com/en-us/library/dd925819%28v=office.12%29.aspx - http://msdn.microsoft.com/en-us/library/windows/desktop/aa380376%28v=vs.85%29.aspx - http://msdn.microsoft.com/en-us/library/aa372045.aspx - http://sedna-soft.de/summary-information-stream/ - http://poi.apache.org/apidocs/org/apache/poi/hpsf/SummaryInformation.html

References for DocumentSummaryInformation stream: - http://msdn.microsoft.com/en-us/library/dd945671%28v=office.12%29.aspx - http://msdn.microsoft.com/en-us/library/windows/desktop/aa380374%28v=vs.85%29.aspx - http://poi.apache.org/apidocs/org/apache/poi/hpsf/DocumentSummaryInformation.html

new in version 0.25

DOCSUM_ATTRIBS = ['codepage_doc', 'category', 'presentation_target', 'bytes', 'lines', 'paragraphs', 'slides', 'notes', 'hidden_slides', 'mm_clips', 'scale_crop', 'heading_pairs', 'titles_of_parts', 'manager', 'company', 'links_dirty', 'chars_with_spaces', 'unused', 'shared_doc', 'link_base', 'hlinks', 'hlinks_changed', 'version', 'dig_sig', 'content_type', 'content_status', 'language', 'doc_version']
SUMMARY_ATTRIBS = ['codepage', 'title', 'subject', 'author', 'keywords', 'comments', 'template', 'last_saved_by', 'revision_number', 'total_edit_time', 'last_printed', 'create_time', 'last_saved_time', 'num_pages', 'num_words', 'num_chars', 'thumbnail', 'creating_application', 'security']
dump()
Dump all metadata, for debugging purposes.

parse_properties(olefile)
Parse standard properties of an OLE file, from the streams “SummaryInformation” and “DocumentSummaryInformation”, if present. Properties are converted to strings, integers or python datetime objects. If a property is not present, its value is set to None.

PIL.OleFileIO.debug(msg)
PIL.OleFileIO.debug_pass(msg)
PIL.OleFileIO.debug_print(msg)
PIL.OleFileIO.filetime2datetime(filetime)
convert FILETIME (64 bits int) to Python datetime.datetime

PIL.OleFileIO.i16(c, o=0)
Converts a 2-bytes (16 bits) string to an integer.

c: string containing bytes to convert o: offset of bytes to convert in string

PIL.OleFileIO.i32(c, o=0)
Converts a 4-bytes (32 bits) string to an integer.

c: string containing bytes to convert o: offset of bytes to convert in string

PIL.OleFileIO.i8(c)
PIL.OleFileIO.isOleFile(filename)
Test if a file is an OLE container (according to the magic bytes in its header).

Parameters:        filename –
string-like or file-like object, OLE file to parse

if filename is a string smaller than 1536 bytes, it is the path of the file to open. (bytes or unicode string)
if filename is a string longer than 1535 bytes, it is parsed as the content of an OLE file in memory. (bytes type only)
if filename is a file-like object (with read and seek methods), it is parsed as-is.
Returns:        True if OLE, False otherwise.
PIL.OleFileIO.set_debug_mode(debug_mode)
Set debug mode on or off, to control display of debugging messages. :param mode: True or False
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 16:21:08 | 显示全部楼层
PyAccess Module
The PyAccess module provides a CFFI/Python implementation of the PixelAccess Class. This implementation is far faster on PyPy than the PixelAccess version.

Note

Accessing individual pixels is fairly slow. If you are looping over all of the pixels in an image, there is likely a faster way using other parts of the Pillow API.
Example
The following script loads an image, accesses one pixel from it, then changes it.

from PIL import Image
im = Image.open('hopper.jpg')
px = im.load()
print (px[4,4])
px[4,4] = (0,0,0)
print (px[4,4])
Results in the following:

(23, 24, 68)
(0, 0, 0)
PyAccess Class
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 16:22:17 | 显示全部楼层
PIL Package (autodoc of remaining modules)
Reference for modules whose documentation has not yet been ported or written can be found here.

BdfFontFile Module
class PIL.BdfFontFile.BdfFontFile(fp)
Bases: PIL.FontFile.FontFile

PIL.BdfFontFile.bdf_char(f)
ContainerIO Module
class PIL.ContainerIO.ContainerIO(file, offset, length)
Bases: object

isatty()
read(n=0)
readline()
readlines()
seek(offset, mode=0)
tell()
FontFile Module
class PIL.FontFile.FontFile
Bases: object

bitmap = None
compile()
Create metrics and bitmap

save(filename)
Save font

PIL.FontFile.puti16(fp, values)
GdImageFile Module
class PIL.GdImageFile.GdImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'GD'
format_description = 'GD uncompressed images'
PIL.GdImageFile.open(fp, mode='r')
GimpGradientFile Module
class PIL.GimpGradientFile.GimpGradientFile(fp)
Bases: PIL.GimpGradientFile.GradientFile

class PIL.GimpGradientFile.GradientFile
Bases: object

getpalette(entries=256)
gradient = None
PIL.GimpGradientFile.curved(middle, pos)
PIL.GimpGradientFile.linear(middle, pos)
PIL.GimpGradientFile.sine(middle, pos)
PIL.GimpGradientFile.sphere_decreasing(middle, pos)
PIL.GimpGradientFile.sphere_increasing(middle, pos)
GimpPaletteFile Module
class PIL.GimpPaletteFile.GimpPaletteFile(fp)
Bases: object

getpalette()
rawmode = 'RGB'
ImageDraw2 Module
class PIL.ImageDraw2.Brush(color, opacity=255)
Bases: object

class PIL.ImageDraw2.Draw(image, size=None, color=None)
Bases: object

arc(xy, start, end, *options)
chord(xy, start, end, *options)
ellipse(xy, *options)
flush()
line(xy, *options)
pieslice(xy, start, end, *options)
polygon(xy, *options)
rectangle(xy, *options)
render(op, xy, pen, brush=None)
settransform(offset)
symbol(xy, symbol, *options)
text(xy, text, font)
textsize(text, font)
class PIL.ImageDraw2.Font(color, file, size=12)
Bases: object

class PIL.ImageDraw2.Pen(color, width=1, opacity=255)
Bases: object

ImageShow Module
class PIL.ImageShow.DisplayViewer
Bases: PIL.ImageShow.UnixViewer

get_command_ex(file, **options)
class PIL.ImageShow.UnixViewer
Bases: PIL.ImageShow.Viewer

show_file(file, **options)
class PIL.ImageShow.Viewer
Bases: object

format = None
get_command(file, **options)
get_format(image)
save_image(image)
show(image, **options)
show_file(file, **options)
show_image(image, **options)
class PIL.ImageShow.XVViewer
Bases: PIL.ImageShow.UnixViewer

get_command_ex(file, title=None, **options)
PIL.ImageShow.register(viewer, order=1)
PIL.ImageShow.show(image, title=None, **options)
PIL.ImageShow.which(executable)
ImageTransform Module
class PIL.ImageTransform.AffineTransform(data)
Bases: PIL.ImageTransform.Transform

method = 0
class PIL.ImageTransform.ExtentTransform(data)
Bases: PIL.ImageTransform.Transform

method = 1
class PIL.ImageTransform.MeshTransform(data)
Bases: PIL.ImageTransform.Transform

method = 4
class PIL.ImageTransform.QuadTransform(data)
Bases: PIL.ImageTransform.Transform

method = 3
class PIL.ImageTransform.Transform(data)
Bases: PIL.Image.ImageTransformHandler

getdata()
transform(size, image, **options)
JpegPresets Module
JPEG quality settings equivalent to the Photoshop settings.

More presets can be added to the presets dict if needed.

Can be use when saving JPEG file.

To apply the preset, specify:

quality="preset_name"
To apply only the quantization table:

qtables="preset_name"
To apply only the subsampling setting:

subsampling="preset_name"
Example:

im.save("image_name.jpg", quality="web_high")
Subsampling
Subsampling is the practice of encoding images by implementing less resolution for chroma information than for luma information. (ref.: https://en.wikipedia.org/wiki/Chroma_subsampling)

Possible subsampling values are 0, 1 and 2 that correspond to 4:4:4, 4:2:2 and 4:1:1 (or 4:2:0?).

You can get the subsampling of a JPEG with the JpegImagePlugin.get_subsampling(im) function.

Quantization tables
They are values use by the DCT (Discrete cosine transform) to remove unnecessary information from the image (the lossy part of the compression). (ref.: https://en.wikipedia.org/wiki/Quantization_matrix#Quantization_matrices, https://en.wikipedia.org/wiki/JPEG#Quantization)

You can get the quantization tables of a JPEG with:

im.quantization
This will return a dict with a number of arrays. You can pass this dict directly as the qtables argument when saving a JPEG.

The tables format between im.quantization and quantization in presets differ in 3 ways:

The base container of the preset is a list with sublists instead of dict. dict[0] -> list[0], dict[1] -> list[1], ...
Each table in a preset is a list instead of an array.
The zigzag order is remove in the preset (needed by libjpeg >= 6a).
You can convert the dict format to the preset format with the JpegImagePlugin.convert_dict_qtables(dict_qtables) function.

Libjpeg ref.: http://www.jpegcameras.com/libjpeg/libjpeg-3.html

PaletteFile Module
class PIL.PaletteFile.PaletteFile(fp)
Bases: object

getpalette()
rawmode = 'RGB'
PcfFontFile Module
class PIL.PcfFontFile.PcfFontFile(fp)
Bases: PIL.FontFile.FontFile

name = 'name'
PIL.PcfFontFile.sz(s, o)
PngImagePlugin.iTXt Class
class PIL.PngImagePlugin.iTXt
Bases: str

Subclass of string to allow iTXt chunks to look like strings while keeping their extra information

__new__(cls, text, lang, tkey)
Parameters:       
value – value for this key
lang – language code
tkey – UTF-8 version of the key name
PngImagePlugin.PngInfo Class
class PIL.PngImagePlugin.PngInfo
Bases: object

PNG chunk container (for use with save(pnginfo=))

add(cid, data)
Appends an arbitrary chunk. Use with caution.

Parameters:       
cid – a byte string, 4 bytes long.
data – a byte string of the encoded data
add_itxt(key, value, lang='', tkey='', zip=False)
Appends an iTXt chunk.

Parameters:       
key – latin-1 encodable text key name
value – value for this key
lang – language code
tkey – UTF-8 version of the key name
zip – compression flag
add_text(key, value, zip=0)
Appends a text chunk.

Parameters:       
key – latin-1 encodable text key name
value – value for this key, text or an PIL.PngImagePlugin.iTXt instance
zip – compression flag
TarIO Module
class PIL.TarIO.TarIO(tarfile, file)
Bases: PIL.ContainerIO.ContainerIO

WalImageFile Module
PIL.WalImageFile.open(filename)
_binary Module
PIL._binary.i16be(c, o=0)
PIL._binary.i16le(c, o=0)
Converts a 2-bytes (16 bits) string to an integer.

c: string containing bytes to convert o: offset of bytes to convert in string

PIL._binary.i32be(c, o=0)
PIL._binary.i32le(c, o=0)
Converts a 4-bytes (32 bits) string to an integer.

c: string containing bytes to convert o: offset of bytes to convert in string

PIL._binary.i8(c)
PIL._binary.o16be(i)
PIL._binary.o16le(i)
PIL._binary.o32be(i)
PIL._binary.o32le(i)
PIL._binary.o8(i)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 16:23:27 | 显示全部楼层
Plugin reference
BmpImagePlugin Module
class PIL.BmpImagePlugin.BmpImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

Image plugin for the Windows Bitmap format (BMP)

BITFIELDS = 3
COMPRESSIONS = {'RLE4': 2, 'JPEG': 4, 'BITFIELDS': 3, 'RAW': 0, 'RLE8': 1, 'PNG': 5}
JPEG = 4
PNG = 5
RAW = 0
RLE4 = 2
RLE8 = 1
format = 'BMP'
format_description = 'Windows Bitmap'
class PIL.BmpImagePlugin.DibImageFile(fp=None, filename=None)
Bases: PIL.BmpImagePlugin.BmpImageFile

format = 'DIB'
format_description = 'Windows Bitmap'
BufrStubImagePlugin Module
class PIL.BufrStubImagePlugin.BufrStubImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.StubImageFile

format = 'BUFR'
format_description = 'BUFR'
PIL.BufrStubImagePlugin.register_handler(handler)
CurImagePlugin Module
class PIL.CurImagePlugin.CurImageFile(fp=None, filename=None)
Bases: PIL.BmpImagePlugin.BmpImageFile

format = 'CUR'
format_description = 'Windows Cursor'
DcxImagePlugin Module
class PIL.DcxImagePlugin.DcxImageFile(fp=None, filename=None)
Bases: PIL.PcxImagePlugin.PcxImageFile

format = 'DCX'
format_description = 'Intel DCX'
is_animated
n_frames
seek(frame)
tell()
EpsImagePlugin Module
class PIL.EpsImagePlugin.EpsImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

EPS File Parser for the Python Imaging Library

format = 'EPS'
format_description = 'Encapsulated Postscript'
load(scale=1)
load_seek(*args, **kwargs)
mode_map = {1: 'L', 2: 'LAB', 3: 'RGB'}
PIL.EpsImagePlugin.Ghostscript(tile, size, fp, scale=1)
Render an image using Ghostscript

class PIL.EpsImagePlugin.PSFile(fp)
Bases: object

Wrapper for bytesio object that treats either CR or LF as end of line.

readline()
seek(offset, whence=0)
PIL.EpsImagePlugin.has_ghostscript()
FitsStubImagePlugin Module
class PIL.FitsStubImagePlugin.FITSStubImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.StubImageFile

format = 'FITS'
format_description = 'FITS'
PIL.FitsStubImagePlugin.register_handler(handler)
FliImagePlugin Module
class PIL.FliImagePlugin.FliImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'FLI'
format_description = 'Autodesk FLI/FLC Animation'
is_animated
n_frames
seek(frame)
tell()
FpxImagePlugin Module
class PIL.FpxImagePlugin.FpxImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'FPX'
format_description = 'FlashPix'
load()
GbrImagePlugin Module
class PIL.GbrImagePlugin.GbrImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'GBR'
format_description = 'GIMP brush file'
load()
GifImagePlugin Module
class PIL.GifImagePlugin.GifImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

data()
format = 'GIF'
format_description = 'Compuserve GIF'
global_palette = None
is_animated
load_end()
n_frames
seek(frame)
tell()
PIL.GifImagePlugin.get_interlace(im)
PIL.GifImagePlugin.getdata(im, offset=(0, 0), **params)
Return a list of strings representing this image. The first string is a local image header, the rest contains encoded image data.

PIL.GifImagePlugin.getheader(im, palette=None, info=None)
Return a list of strings representing a GIF header

GribStubImagePlugin Module
class PIL.GribStubImagePlugin.GribStubImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.StubImageFile

format = 'GRIB'
format_description = 'GRIB'
PIL.GribStubImagePlugin.register_handler(handler)
Hdf5StubImagePlugin Module
class PIL.Hdf5StubImagePlugin.HDF5StubImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.StubImageFile

format = 'HDF5'
format_description = 'HDF5'
PIL.Hdf5StubImagePlugin.register_handler(handler)
IcnsImagePlugin Module
class PIL.IcnsImagePlugin.IcnsFile(fobj)
Bases: object

SIZES = {(256, 256, 1): [('ic08', <function read_png_or_jpeg2000 at 0x7f9f3a770758>)], (128, 128, 2): [('ic13', <function read_png_or_jpeg2000 at 0x7f9f3a770758>)], (64, 64, 1): [('icp6', <function read_png_or_jpeg2000 at 0x7f9f3a770758>)], (128, 128, 1): [('ic07', <function read_png_or_jpeg2000 at 0x7f9f3a770758>), ('it32', <function read_32t at 0x7f9f3a7705f0>), ('t8mk', <function read_mk at 0x7f9f3a7706e0>)], (32, 32, 1): [('icp5', <function read_png_or_jpeg2000 at 0x7f9f3a770758>), ('il32', <function read_32 at 0x7f9f3a770668>), ('l8mk', <function read_mk at 0x7f9f3a7706e0>)], (16, 16, 2): [('ic11', <function read_png_or_jpeg2000 at 0x7f9f3a770758>)], (512, 512, 2): [('ic10', <function read_png_or_jpeg2000 at 0x7f9f3a770758>)], (512, 512, 1): [('ic09', <function read_png_or_jpeg2000 at 0x7f9f3a770758>)], (48, 48, 1): [('ih32', <function read_32 at 0x7f9f3a770668>), ('h8mk', <function read_mk at 0x7f9f3a7706e0>)], (256, 256, 2): [('ic14', <function read_png_or_jpeg2000 at 0x7f9f3a770758>)], (16, 16, 1): [('icp4', <function read_png_or_jpeg2000 at 0x7f9f3a770758>), ('is32', <function read_32 at 0x7f9f3a770668>), ('s8mk', <function read_mk at 0x7f9f3a7706e0>)], (32, 32, 2): [('ic12', <function read_png_or_jpeg2000 at 0x7f9f3a770758>)]}
bestsize()
dataforsize(size)
Get an icon resource as {channel: array}. Note that the arrays are bottom-up like windows bitmaps and will likely need to be flipped or transposed in some way.

getimage(size=None)
itersizes()
class PIL.IcnsImagePlugin.IcnsImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

PIL image support for Mac OS .icns files. Chooses the best resolution, but will possibly load a different size image if you mutate the size attribute before calling ‘load’.

The info dictionary has a key ‘sizes’ that is a list of sizes that the icns file has.

format = 'ICNS'
format_description = 'Mac OS icns resource'
load()
PIL.IcnsImagePlugin.nextheader(fobj)
PIL.IcnsImagePlugin.read_32(fobj, start_length, size)
Read a 32bit RGB icon resource. Seems to be either uncompressed or an RLE packbits-like scheme.

PIL.IcnsImagePlugin.read_32t(fobj, start_length, size)
PIL.IcnsImagePlugin.read_mk(fobj, start_length, size)
PIL.IcnsImagePlugin.read_png_or_jpeg2000(fobj, start_length, size)
IcoImagePlugin Module
class PIL.IcoImagePlugin.IcoFile(buf)
Bases: object

frame(idx)
Get an image from frame idx

getimage(size, bpp=False)
Get an image from the icon

sizes()
Get a list of all available icon sizes and color depths.

class PIL.IcoImagePlugin.IcoImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

PIL read-only image support for Microsoft Windows .ico files.

By default the largest resolution image in the file will be loaded. This can be changed by altering the ‘size’ attribute before calling ‘load’.

The info dictionary has a key ‘sizes’ that is a list of the sizes available in the icon file.

Handles classic, XP and Vista icon formats.

This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis <casadebender@gmail.com>. https://code.google.com/p/casadebender/wiki/Win32IconImagePlugin

format = 'ICO'
format_description = 'Windows Icon'
load()
load_seek()
ImImagePlugin Module
class PIL.ImImagePlugin.ImImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'IM'
format_description = 'IFUNC Image Memory'
is_animated
n_frames
seek(frame)
tell()
PIL.ImImagePlugin.number(s)
ImtImagePlugin Module
class PIL.ImtImagePlugin.ImtImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'IMT'
format_description = 'IM Tools'
IptcImagePlugin Module
class PIL.IptcImagePlugin.IptcImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

field()
format = 'IPTC'
format_description = 'IPTC/NAA'
getint(key)
load()
PIL.IptcImagePlugin.dump(c)
PIL.IptcImagePlugin.getiptcinfo(im)
PIL.IptcImagePlugin.i(c)
JpegImagePlugin Module
PIL.JpegImagePlugin.APP(self, marker)
PIL.JpegImagePlugin.COM(self, marker)
PIL.JpegImagePlugin.DQT(self, marker)
class PIL.JpegImagePlugin.JpegImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

draft(mode, size)
format = 'JPEG'
format_description = 'JPEG (ISO 10918)'
load_djpeg()
PIL.JpegImagePlugin.SOF(self, marker)
PIL.JpegImagePlugin.Skip(self, marker)
PIL.JpegImagePlugin.convert_dict_qtables(qtables)
PIL.JpegImagePlugin.get_sampling(im)
PIL.JpegImagePlugin.jpeg_factory(fp=None, filename=None)
Jpeg2KImagePlugin Module
class PIL.Jpeg2KImagePlugin.Jpeg2KImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'JPEG2000'
format_description = 'JPEG 2000 (ISO 15444)'
load()
McIdasImagePlugin Module
class PIL.McIdasImagePlugin.McIdasImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'MCIDAS'
format_description = 'McIdas area file'
MicImagePlugin Module
class PIL.MicImagePlugin.MicImageFile(fp=None, filename=None)
Bases: PIL.TiffImagePlugin.TiffImageFile

format = 'MIC'
format_description = 'Microsoft Image Composer'
is_animated
n_frames
seek(frame)
tell()
MpegImagePlugin Module
class PIL.MpegImagePlugin.BitStream(fp)
Bases: object

next()
peek(bits)
read(bits)
skip(bits)
class PIL.MpegImagePlugin.MpegImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'MPEG'
format_description = 'MPEG'
MspImagePlugin Module
class PIL.MspImagePlugin.MspImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'MSP'
format_description = 'Windows Paint'
PalmImagePlugin Module
PIL.PalmImagePlugin.build_prototype_image()
PcdImagePlugin Module
class PIL.PcdImagePlugin.PcdImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'PCD'
format_description = 'Kodak PhotoCD'
PcxImagePlugin Module
class PIL.PcxImagePlugin.PcxImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'PCX'
format_description = 'Paintbrush'
PdfImagePlugin Module
PixarImagePlugin Module
class PIL.PixarImagePlugin.PixarImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'PIXAR'
format_description = 'PIXAR raster image'
PngImagePlugin Module
PIL.PngImagePlugin.getchunks(im, **params)
Return a list of PNG chunks representing this image.

PIL.PngImagePlugin.is_cid()
match(string[, pos[, endpos]]) –> match object or None. Matches zero or more characters at the beginning of the string

PIL.PngImagePlugin.putchunk(fp, cid, *data)
Write a PNG chunk (including CRC field)

class PIL.PngImagePlugin.ChunkStream(fp)
Bases: object

call(cid, pos, length)
Call the appropriate chunk handler

close()
crc(cid, data)
Read and verify checksum

crc_skip(cid, data)
Read checksum. Used if the C module is not present

push(cid, pos, length)
read()
Fetch a new chunk. Returns header information.

verify(endchunk='IEND')
class PIL.PngImagePlugin.PngImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'PNG'
format_description = 'Portable network graphics'
load_end()
internal: finished reading image data

load_prepare()
internal: prepare to read PNG file

load_read(read_bytes)
internal: read more image data

verify()
Verify PNG file

class PIL.PngImagePlugin.PngStream(fp)
Bases: PIL.PngImagePlugin.ChunkStream

check_text_memory(chunklen)
chunk_IDAT(pos, length)
chunk_IEND(pos, length)
chunk_IHDR(pos, length)
chunk_PLTE(pos, length)
chunk_gAMA(pos, length)
chunk_iCCP(pos, length)
chunk_iTXt(pos, length)
chunk_pHYs(pos, length)
chunk_tEXt(pos, length)
chunk_tRNS(pos, length)
chunk_zTXt(pos, length)
PpmImagePlugin Module
class PIL.PpmImagePlugin.PpmImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'PPM'
format_description = 'Pbmplus image'
PsdImagePlugin Module
class PIL.PsdImagePlugin.PsdImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'PSD'
format_description = 'Adobe Photoshop'
is_animated
load_prepare()
n_frames
seek(layer)
tell()
SgiImagePlugin Module
class PIL.SgiImagePlugin.SgiImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'SGI'
format_description = 'SGI Image File Format'
SpiderImagePlugin Module
class PIL.SpiderImagePlugin.SpiderImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

convert2byte(depth=255)
format = 'SPIDER'
format_description = 'Spider 2D image'
is_animated
n_frames
seek(frame)
tell()
tkPhotoImage()
PIL.SpiderImagePlugin.isInt(f)
PIL.SpiderImagePlugin.isSpiderHeader(t)
PIL.SpiderImagePlugin.isSpiderImage(filename)
PIL.SpiderImagePlugin.loadImageSeries(filelist=None)
create a list of Image.images for use in montage

PIL.SpiderImagePlugin.makeSpiderHeader(im)
SunImagePlugin Module
class PIL.SunImagePlugin.SunImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'SUN'
format_description = 'Sun Raster File'
TgaImagePlugin Module
class PIL.TgaImagePlugin.TgaImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'TGA'
format_description = 'Targa'
TiffImagePlugin Module
class PIL.TiffImagePlugin.IFDRational(value, denominator=1)
Bases: numbers.Rational

Implements a rational class where 0/0 is a legal value to match the in the wild use of exif rationals.

e.g., DigitalZoomRatio - 0.00/0.00 indicates that no digital zoom was used

denominator
limit_rational(max_denominator)
Parameters:        max_denominator – Integer, the maximum denominator value
Returns:        Tuple of (numerator, denominator)
numerator
PIL.TiffImagePlugin.ImageFileDirectory
alias of ImageFileDirectory_v1

class PIL.TiffImagePlugin.ImageFileDirectory_v1(*args, **kwargs)
Bases: PIL.TiffImagePlugin.ImageFileDirectory_v2

This class represents the legacy interface to a TIFF tag directory.

Exposes a dictionary interface of the tags in the directory:

ifd = ImageFileDirectory_v1()
ifd[key] = 'Some Data'
ifd.tagtype[key] = 2
print ifd[key]
('Some Data',)
Also contains a dictionary of tag types as read from the tiff image file, ~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype.

Values are returned as a tuple.

Deprecated since version 3.0.0.

classmethod from_v2(original)
Returns an ImageFileDirectory_v1 instance with the same data as is contained in the original ImageFileDirectory_v2 instance.

Returns:        ImageFileDirectory_v1
tagdata
tags
to_v2()
Returns an ImageFileDirectory_v2 instance with the same data as is contained in the original ImageFileDirectory_v1 instance.

Returns:        ImageFileDirectory_v2
class PIL.TiffImagePlugin.ImageFileDirectory_v2(ifh='II*x00x00x00x00x00', prefix=None)
Bases: _abcoll.MutableMapping

This class represents a TIFF tag directory. To speed things up, we don’t decode tags unless they’re asked for.

Exposes a dictionary interface of the tags in the directory:

ifd = ImageFileDirectory_v2()
ifd[key] = 'Some Data'
ifd.tagtype[key] = 2
print(ifd[key])
'Some Data'
Individual values are returned as the strings or numbers, sequences are returned as tuples of the values.

The tiff metadata type of each item is stored in a dictionary of tag types in ~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype. The types are read from a tiff file, guessed from the type added, or added manually.

Data Structures:

self.tagtype = {}
Key: numerical tiff tag number
Value: integer corresponding to the data type from ~PIL.TiffTags.TYPES
New in version 3.0.0.

as_dict()
Return a dictionary of the image’s tags.

use dict(ifd) instead.

Deprecated since version 3.0.0.

has_key(tag)
legacy_api
load(fp)
load_byte(data, legacy_api=True)
load_double(data, legacy_api=True)
load_float(data, legacy_api=True)
load_long(data, legacy_api=True)
load_rational(data, legacy_api=True)
load_short(data, legacy_api=True)
load_signed_byte(data, legacy_api=True)
load_signed_long(data, legacy_api=True)
load_signed_rational(data, legacy_api=True)
load_signed_short(data, legacy_api=True)
load_string(data, legacy_api=True)
load_undefined(data, legacy_api=True)
named()
Returns:        dict of name|key: value
Returns the complete tag dictionary, with named tags where possible.

offset
prefix
reset()
save(fp)
write_byte(data)
write_double(*values)
write_float(*values)
write_long(*values)
write_rational(*values)
write_short(*values)
write_signed_byte(*values)
write_signed_long(*values)
write_signed_rational(*values)
write_signed_short(*values)
write_string(value)
write_undefined(value)
class PIL.TiffImagePlugin.TiffImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'TIFF'
format_description = 'Adobe TIFF'
is_animated
n_frames
seek(frame)
Select a given frame as current image

tell()
Return the current frame number

WebPImagePlugin Module
class PIL.WebPImagePlugin.WebPImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'WEBP'
format_description = 'WebP image'
WmfImagePlugin Module
class PIL.WmfImagePlugin.WmfStubImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.StubImageFile

format = 'WMF'
format_description = 'Windows Metafile'
PIL.WmfImagePlugin.register_handler(handler)
PIL.WmfImagePlugin.short(c, o=0)
XVThumbImagePlugin Module
class PIL.XVThumbImagePlugin.XVThumbImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'XVThumb'
format_description = 'XV thumbnail image'
XbmImagePlugin Module
class PIL.XbmImagePlugin.XbmImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'XBM'
format_description = 'X11 Bitmap'
XpmImagePlugin Module

class PIL.XpmImagePlugin.XpmImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'XPM'
format_description = 'X11 Pixel Map'
load_read(bytes)
Next  Previous
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-11-19 19:35:12 | 显示全部楼层
这是啥?高大上啊~
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-3-28 19:54:49 | 显示全部楼层
阿巴阿巴,看不懂
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-27 12:22

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表