Cleanup WS, courtesy of @Arfrever

find * -type f "-(" -name "*.bdf" -o -name "*.c" -o -name "*.h" -o -name "*.py" -o -name "*.rst" -o -name "*.txt" "-)" -exec sed -e "s/[[:space:]]*$//" -i {} \;
This commit is contained in:
Alex Clark 2013-06-30 18:42:19 -04:00
parent d92e2737f7
commit bb1b3a532c
89 changed files with 450 additions and 450 deletions

View File

@ -1,13 +1,13 @@
STARTFONT 2.1 STARTFONT 2.1
COMMENT $XConsortium: courB08.bdf,v 1.5 94/04/10 21:46:11 gildea Exp $ COMMENT $XConsortium: courB08.bdf,v 1.5 94/04/10 21:46:11 gildea Exp $
COMMENT COMMENT
COMMENT Copyright 1984, 1987 Adobe Systems, Inc. COMMENT Copyright 1984, 1987 Adobe Systems, Inc.
COMMENT Portions Copyright 1988 Digital Equipment Corporation COMMENT Portions Copyright 1988 Digital Equipment Corporation
COMMENT COMMENT
COMMENT Adobe is a registered trademark of Adobe Systems, Inc. Permission COMMENT Adobe is a registered trademark of Adobe Systems, Inc. Permission
COMMENT to use these trademarks is hereby granted only in association with the COMMENT to use these trademarks is hereby granted only in association with the
COMMENT images described in this file. COMMENT images described in this file.
COMMENT COMMENT
COMMENT Permission to use, copy, modify, and distribute this software and COMMENT Permission to use, copy, modify, and distribute this software and
COMMENT its documentation for any purpose and without fee is hereby granted, COMMENT its documentation for any purpose and without fee is hereby granted,
COMMENT provided that the above copyright notices appear in all copies and COMMENT provided that the above copyright notices appear in all copies and
@ -19,7 +19,7 @@ COMMENT specific, written prior permission. Adobe Systems and Digital
COMMENT Equipment Corporation make no representations about the suitability COMMENT Equipment Corporation make no representations about the suitability
COMMENT of this software for any purpose. It is provided "as is" without COMMENT of this software for any purpose. It is provided "as is" without
COMMENT express or implied warranty. COMMENT express or implied warranty.
COMMENT COMMENT
COMMENT ADOBE SYSTEMS AND DIGITAL EQUIPMENT CORPORATION DISCLAIM ALL COMMENT ADOBE SYSTEMS AND DIGITAL EQUIPMENT CORPORATION DISCLAIM ALL
COMMENT WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED COMMENT WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED
COMMENT WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL ADOBE COMMENT WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL ADOBE
@ -28,8 +28,8 @@ COMMENT INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
COMMENT RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF COMMENT RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
COMMENT CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN COMMENT CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
COMMENT CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. COMMENT CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
COMMENT COMMENT
COMMENT COMMENT
FONT -Adobe-Courier-Bold-R-Normal--11-80-100-100-M-60-ISO8859-1 FONT -Adobe-Courier-Bold-R-Normal--11-80-100-100-M-60-ISO8859-1
SIZE 8 100 100 SIZE 8 100 100
FONTBOUNDINGBOX 8 11 -1 -2 FONTBOUNDINGBOX 8 11 -1 -2

View File

@ -288,7 +288,7 @@ def _save(im, fp, filename):
break break
else: else:
transparentColorExists = False transparentColorExists = False
# transparency extension block # transparency extension block
if transparentColorExists: if transparentColorExists:
fp.write(b"!" + fp.write(b"!" +
@ -353,7 +353,7 @@ def getheader(im, palette=None, info=None):
# if the user adds a palette, use it # if the user adds a palette, use it
usedPaletteColors = None usedPaletteColors = None
if palette is not None and isinstance(palette, bytes): if palette is not None and isinstance(palette, bytes):
paletteBytes = palette[:768] paletteBytes = palette[:768]
else: else:

View File

@ -44,12 +44,12 @@ class IcoFile:
""" """
Parse image from file-like object containing ico file data Parse image from file-like object containing ico file data
""" """
# check magic # check magic
s = buf.read(6) s = buf.read(6)
if not _accept(s): if not _accept(s):
raise SyntaxError("not an ICO file") raise SyntaxError("not an ICO file")
self.buf = buf self.buf = buf
self.entry = [] self.entry = []
@ -59,7 +59,7 @@ class IcoFile:
# Get headers for each item # Get headers for each item
for i in range(self.nb_items): for i in range(self.nb_items):
s = buf.read(16) s = buf.read(16)
icon_header = { icon_header = {
'width': i8(s[0]), 'width': i8(s[0]),
'height': i8(s[1]), 'height': i8(s[1]),
@ -70,33 +70,33 @@ class IcoFile:
'size': i32(s[8:]), 'size': i32(s[8:]),
'offset': i32(s[12:]) 'offset': i32(s[12:])
} }
# See Wikipedia # See Wikipedia
for j in ('width', 'height'): for j in ('width', 'height'):
if not icon_header[j]: if not icon_header[j]:
icon_header[j] = 256 icon_header[j] = 256
# See Wikipedia notes about color depth. # See Wikipedia notes about color depth.
# We need this just to differ images with equal sizes # We need this just to differ images with equal sizes
icon_header['color_depth'] = (icon_header['bpp'] or (icon_header['nb_color'] != 0 and ceil(log(icon_header['nb_color'],2))) or 256) icon_header['color_depth'] = (icon_header['bpp'] or (icon_header['nb_color'] != 0 and ceil(log(icon_header['nb_color'],2))) or 256)
icon_header['dim'] = (icon_header['width'], icon_header['height']) icon_header['dim'] = (icon_header['width'], icon_header['height'])
icon_header['square'] = icon_header['width'] * icon_header['height'] icon_header['square'] = icon_header['width'] * icon_header['height']
self.entry.append(icon_header) self.entry.append(icon_header)
self.entry = sorted(self.entry, key=lambda x: x['color_depth']) self.entry = sorted(self.entry, key=lambda x: x['color_depth'])
# ICO images are usually squares # ICO images are usually squares
# self.entry = sorted(self.entry, key=lambda x: x['width']) # self.entry = sorted(self.entry, key=lambda x: x['width'])
self.entry = sorted(self.entry, key=lambda x: x['square']) self.entry = sorted(self.entry, key=lambda x: x['square'])
self.entry.reverse() self.entry.reverse()
def sizes(self): def sizes(self):
""" """
Get a list of all available icon sizes and color depths. Get a list of all available icon sizes and color depths.
""" """
return set((h['width'], h['height']) for h in self.entry) return set((h['width'], h['height']) for h in self.entry)
def getimage(self, size, bpp=False): def getimage(self, size, bpp=False):
""" """
Get an image from the icon Get an image from the icon
@ -105,30 +105,30 @@ class IcoFile:
if size == h['dim'] and (bpp == False or bpp == h['color_depth']): if size == h['dim'] and (bpp == False or bpp == h['color_depth']):
return self.frame(i) return self.frame(i)
return self.frame(0) return self.frame(0)
def frame(self, idx): def frame(self, idx):
""" """
Get an image from frame idx Get an image from frame idx
""" """
header = self.entry[idx] header = self.entry[idx]
self.buf.seek(header['offset']) self.buf.seek(header['offset'])
data = self.buf.read(8) data = self.buf.read(8)
self.buf.seek(header['offset']) self.buf.seek(header['offset'])
if data[:8] == PngImagePlugin._MAGIC: if data[:8] == PngImagePlugin._MAGIC:
# png frame # png frame
im = PngImagePlugin.PngImageFile(self.buf) im = PngImagePlugin.PngImageFile(self.buf)
else: else:
# XOR + AND mask bmp frame # XOR + AND mask bmp frame
im = BmpImagePlugin.DibImageFile(self.buf) im = BmpImagePlugin.DibImageFile(self.buf)
# change tile dimension to only encompass XOR image # change tile dimension to only encompass XOR image
im.size = (im.size[0], int(im.size[1] / 2)) im.size = (im.size[0], int(im.size[1] / 2))
d, e, o, a = im.tile[0] d, e, o, a = im.tile[0]
im.tile[0] = d, (0,0) + im.size, o, a im.tile[0] = d, (0,0) + im.size, o, a
# figure out where AND mask image starts # figure out where AND mask image starts
mode = a[0] mode = a[0]
bpp = 8 bpp = 8
@ -136,7 +136,7 @@ class IcoFile:
if mode == BmpImagePlugin.BIT2MODE[k][1]: if mode == BmpImagePlugin.BIT2MODE[k][1]:
bpp = k bpp = k
break break
if 32 == bpp: if 32 == bpp:
# 32-bit color depth icon image allows semitransparent areas # 32-bit color depth icon image allows semitransparent areas
# PIL's DIB format ignores transparency bits, recover them # PIL's DIB format ignores transparency bits, recover them
@ -161,7 +161,7 @@ class IcoFile:
if (w % 32) > 0: if (w % 32) > 0:
# bitmap row data is aligned to word boundaries # bitmap row data is aligned to word boundaries
w += 32 - (im.size[0] % 32) w += 32 - (im.size[0] % 32)
# the total mask data is padded row size * height / bits per char # the total mask data is padded row size * height / bits per char
and_mask_offset = o + int(im.size[0] * im.size[1] * (bpp / 8.0)) and_mask_offset = o + int(im.size[0] * im.size[1] * (bpp / 8.0))
@ -178,15 +178,15 @@ class IcoFile:
'raw', # raw decoder 'raw', # raw decoder
('1;I', int(w/8), -1) # 1bpp inverted, padded, reversed ('1;I', int(w/8), -1) # 1bpp inverted, padded, reversed
) )
# now we have two images, im is XOR image and mask is AND image # now we have two images, im is XOR image and mask is AND image
# apply mask image as alpha channel # apply mask image as alpha channel
im = im.convert('RGBA') im = im.convert('RGBA')
im.putalpha(mask) im.putalpha(mask)
return im return im
## ##
# Image plugin for Windows Icon files. # Image plugin for Windows Icon files.
@ -194,14 +194,14 @@ class IcoImageFile(ImageFile.ImageFile):
""" """
PIL read-only image support for Microsoft Windows .ico files. PIL read-only image support for Microsoft Windows .ico files.
By default the largest resolution image in the file will be loaded. This can By default the largest resolution image in the file will be loaded. This can
be changed by altering the 'size' attribute before calling 'load'. 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 The info dictionary has a key 'sizes' that is a list of the sizes available
in the icon file. in the icon file.
Handles classic, XP and Vista icon formats. Handles classic, XP and Vista icon formats.
This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis <casadebender@gmail.com>. This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis <casadebender@gmail.com>.
https://code.google.com/p/casadebender/wiki/Win32IconImagePlugin https://code.google.com/p/casadebender/wiki/Win32IconImagePlugin
""" """

View File

@ -213,7 +213,7 @@ class ImageFile(Image.Image):
# JpegDecode needs to clean things up here either way # JpegDecode needs to clean things up here either way
# If we don't destroy the decompressor, we have a memory leak. # If we don't destroy the decompressor, we have a memory leak.
d.cleanup() d.cleanup()
if LOAD_TRUNCATED_IMAGES: if LOAD_TRUNCATED_IMAGES:
break break
else: else:
@ -450,7 +450,7 @@ def _save(im, fp, tile, bufsize=0):
# FIXME: make MAXBLOCK a configuration parameter # FIXME: make MAXBLOCK a configuration parameter
# It would be great if we could have the encoder specifiy what it needs # It would be great if we could have the encoder specifiy what it needs
# But, it would need at least the image size in most cases. RawEncode is # But, it would need at least the image size in most cases. RawEncode is
# a tricky case. # a tricky case.
bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c
try: try:
fh = fp.fileno() fh = fp.fileno()

View File

@ -563,7 +563,7 @@ def _save(im, fp, filename):
bufsize=0 bufsize=0
if "optimize" in info: if "optimize" in info:
bufsize = im.size[0]*im.size[1] bufsize = im.size[0]*im.size[1]
# The exif info needs to be written as one block, + APP1, + one spare byte. # The exif info needs to be written as one block, + APP1, + one spare byte.
# Ensure that our buffer is big enough # Ensure that our buffer is big enough
bufsize = max(ImageFile.MAXBLOCK, bufsize, len(info.get("exif",b"")) + 5 ) bufsize = max(ImageFile.MAXBLOCK, bufsize, len(info.get("exif",b"")) + 5 )

View File

@ -145,13 +145,13 @@ presets = {
]}, ]},
'web_maximum': {'subsampling': 0, # "4:4:4" 'web_maximum': {'subsampling': 0, # "4:4:4"
'quantization': [ 'quantization': [
[ 1, 1, 1, 1, 1, 1, 1, 1, [ 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2,
1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 2, 2,
1, 1, 1, 1, 1, 2, 2, 3, 1, 1, 1, 1, 1, 2, 2, 3,
1, 1, 1, 1, 2, 2, 3, 3, 1, 1, 1, 1, 2, 2, 3, 3,
1, 1, 1, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 3, 3, 3,
1, 1, 2, 2, 3, 3, 3, 3], 1, 1, 2, 2, 3, 3, 3, 3],
[ 1, 1, 1, 2, 2, 3, 3, 3, [ 1, 1, 1, 2, 2, 3, 3, 3,
1, 1, 1, 2, 3, 3, 3, 3, 1, 1, 1, 2, 3, 3, 3, 3,
@ -159,7 +159,7 @@ presets = {
2, 2, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 3, 3,
2, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3] 3, 3, 3, 3, 3, 3, 3, 3]
]}, ]},
'low': {'subsampling': 2, # "4:1:1" 'low': {'subsampling': 2, # "4:1:1"
@ -203,7 +203,7 @@ presets = {
'high': {'subsampling': 0, # "4:4:4" 'high': {'subsampling': 0, # "4:4:4"
'quantization': [ 'quantization': [
[ 6, 4, 4, 6, 9, 11, 12, 16, [ 6, 4, 4, 6, 9, 11, 12, 16,
4, 5, 5, 6, 8, 10, 12, 12, 4, 5, 5, 6, 8, 10, 12, 12,
4, 5, 5, 6, 10, 12, 12, 12, 4, 5, 5, 6, 10, 12, 12, 12,
6, 6, 6, 11, 12, 12, 12, 12, 6, 6, 6, 11, 12, 12, 12, 12,
9, 8, 10, 12, 12, 12, 12, 12, 9, 8, 10, 12, 12, 12, 12, 12,

View File

@ -55,7 +55,7 @@ class PsdImageFile(ImageFile.ImageFile):
format_description = "Adobe Photoshop" format_description = "Adobe Photoshop"
def _open(self): def _open(self):
read = self.fp.read read = self.fp.read
# #

View File

@ -12,14 +12,14 @@ _VALID_WEBP_MODES = {
_VP8_MODES_BY_IDENTIFIER = { _VP8_MODES_BY_IDENTIFIER = {
b"VP8 ": "RGB", b"VP8 ": "RGB",
b"VP8X": "RGBA", b"VP8X": "RGBA",
} }
def _accept(prefix): def _accept(prefix):
is_riff_file_format = prefix[:4] == b"RIFF" is_riff_file_format = prefix[:4] == b"RIFF"
is_webp_file = prefix[8:12] == b"WEBP" is_webp_file = prefix[8:12] == b"WEBP"
is_valid_vp8_mode = prefix[12:16] in _VP8_MODES_BY_IDENTIFIER is_valid_vp8_mode = prefix[12:16] in _VP8_MODES_BY_IDENTIFIER
return is_riff_file_format and is_webp_file and is_valid_vp8_mode return is_riff_file_format and is_webp_file and is_valid_vp8_mode
@ -28,7 +28,7 @@ class WebPImageFile(ImageFile.ImageFile):
format = "WEBP" format = "WEBP"
format_description = "WebP image" format_description = "WebP image"
def _open(self): def _open(self):
data, width, height, self.mode = _webp.WebPDecode(self.fp.read()) data, width, height, self.mode = _webp.WebPDecode(self.fp.read())
self.size = width, height self.size = width, height
self.fp = BytesIO(data) self.fp = BytesIO(data)
@ -39,9 +39,9 @@ def _save(im, fp, filename):
image_mode = im.mode image_mode = im.mode
if im.mode not in _VALID_WEBP_MODES: if im.mode not in _VALID_WEBP_MODES:
raise IOError("cannot write mode %s as WEBP" % image_mode) raise IOError("cannot write mode %s as WEBP" % image_mode)
quality = im.encoderinfo.get("quality", 80) quality = im.encoderinfo.get("quality", 80)
data = _webp.WebPEncode( data = _webp.WebPEncode(
im.tobytes(), im.tobytes(),
im.size[0], im.size[0],

View File

@ -32,7 +32,7 @@ What about image code bugs?
Please report any non-packaging related issues here first: Please report any non-packaging related issues here first:
- https://bitbucket.org/effbot/pil-2009-raclette/issues - https://bitbucket.org/effbot/pil-2009-raclette/issues
Then open a ticket here: Then open a ticket here:
@ -70,7 +70,7 @@ PIL needs you! Please help us maintain the Python Imaging Library here:
Support Support
~~~~~~~ ~~~~~~~
If you don't want to help with development, you can help us financially. Your donation will be very much appreciated. If you don't want to help with development, you can help us financially. Your donation will be very much appreciated.
.. Note:: New contributors: please add your name (and donation preference) here and send a pull request. .. Note:: New contributors: please add your name (and donation preference) here and send a pull request.
@ -82,7 +82,7 @@ Pillow is a (labor of love) volunteer effort led by Alex Clark. Any contributor
| Alex Clark (fork author) | http://gittip.com/aclark4life | | Alex Clark (fork author) | http://gittip.com/aclark4life |
+--------------------------------------+---------------------------------------+ +--------------------------------------+---------------------------------------+
Developer Developer
--------- ---------
.. Note:: If there is a binary package for your system, that is the easiest way to install Pillow. Currently we only provide binaries for Windows (via Python eggs). .. Note:: If there is a binary package for your system, that is the easiest way to install Pillow. Currently we only provide binaries for Windows (via Python eggs).
@ -104,13 +104,13 @@ Some (most?) of Pillow's features require external libraries.
* **libfreetype** provides type related services * **libfreetype** provides type related services
* **littlecms** provides color management * **littlecms** provides color management
* **libwebp** provides the Webp format. * **libwebp** provides the Webp format.
* Pillow has been tested with version **0.1.3**, which does not read transparent webp files. Version **0.3.0** supports transparency. * Pillow has been tested with version **0.1.3**, which does not read transparent webp files. Version **0.3.0** supports transparency.
If the prerequisites are installed in the standard library locations for your machine (e.g. /usr or /usr/local), no additional configuration should be required. If they are installed in a non-standard location, you may need to configure setuptools to use those locations (i.e. by editing setup.py and/or setup.cfg). Once you have installed the prerequisites, run:: If the prerequisites are installed in the standard library locations for your machine (e.g. /usr or /usr/local), no additional configuration should be required. If they are installed in a non-standard location, you may need to configure setuptools to use those locations (i.e. by editing setup.py and/or setup.cfg). Once you have installed the prerequisites, run::
$ pip install Pillow $ pip install Pillow
@ -372,12 +372,12 @@ Python Imaging Library
http://www.gzip.org/zlib/ http://www.gzip.org/zlib/
OpenType/TrueType freetype2 (2.3.9 or later is recommended) OpenType/TrueType freetype2 (2.3.9 or later is recommended)
support support
http://www.freetype.org http://www.freetype.org
http://freetype.sourceforge.net http://freetype.sourceforge.net
CMS support littleCMS (1.1.5 or later is recommended) CMS support littleCMS (1.1.5 or later is recommended)
support support
http://www.littlecms.com/ http://www.littlecms.com/
If you have a recent Linux version, the libraries provided with the If you have a recent Linux version, the libraries provided with the
@ -403,7 +403,7 @@ Python Imaging Library
http://www.python.org/sigs/distutils-sig/download.html http://www.python.org/sigs/distutils-sig/download.html
You can fetch distutils 1.0.2 from the Python source repository: You can fetch distutils 1.0.2 from the Python source repository:
svn export http://svn.python.org/projects/python/tags/Distutils-1_0_2/Lib/distutils/ svn export http://svn.python.org/projects/python/tags/Distutils-1_0_2/Lib/distutils/
For newer releases, the distutils library is included in the For newer releases, the distutils library is included in the
@ -412,7 +412,7 @@ Python Imaging Library
NOTE: Version 1.1.7 is not fully compatible with 1.5.2. Some NOTE: Version 1.1.7 is not fully compatible with 1.5.2. Some
more recent additions to the library may not work, but the core more recent additions to the library may not work, but the core
functionality is available. functionality is available.
3. If you didn't build Python from sources, make sure you have 3. If you didn't build Python from sources, make sure you have
Python's build support files on your machine. If you've down- Python's build support files on your machine. If you've down-

View File

@ -7,10 +7,10 @@ documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in both that copyright notice and this permission notice appear in
supporting documentation, and that the name of A.M. Kuchling and supporting documentation, and that the name of A.M. Kuchling and
Ralph Heinkel not be used in advertising or publicity pertaining to Ralph Heinkel not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission. distribution of the software without specific, written prior permission.
A.M. KUCHLING, R.H. HEINKEL DISCLAIM ALL WARRANTIES WITH REGARD TO THIS A.M. KUCHLING, R.H. HEINKEL DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS,
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
@ -46,11 +46,11 @@ PyThreadState *_save;
#endif #endif
/* Raise a SANE exception */ /* Raise a SANE exception */
PyObject * PyObject *
PySane_Error(SANE_Status st) PySane_Error(SANE_Status st)
{ {
const char *string; const char *string;
if (st==SANE_STATUS_GOOD) {Py_INCREF(Py_None); return (Py_None);} if (st==SANE_STATUS_GOOD) {Py_INCREF(Py_None); return (Py_None);}
string=sane_strstatus(st); string=sane_strstatus(st);
PyErr_SetString(ErrorObject, string); PyErr_SetString(ErrorObject, string);
@ -103,7 +103,7 @@ SaneDev_get_parameters(SaneDevObject *self, PyObject *args)
SANE_Status st; SANE_Status st;
SANE_Parameters p; SANE_Parameters p;
char *format="unknown format"; char *format="unknown format";
if (!PyArg_ParseTuple(args, "")) if (!PyArg_ParseTuple(args, ""))
return NULL; return NULL;
if (self->h==NULL) if (self->h==NULL)
@ -114,7 +114,7 @@ SaneDev_get_parameters(SaneDevObject *self, PyObject *args)
Py_BEGIN_ALLOW_THREADS Py_BEGIN_ALLOW_THREADS
st=sane_get_parameters(self->h, &p); st=sane_get_parameters(self->h, &p);
Py_END_ALLOW_THREADS Py_END_ALLOW_THREADS
if (st) return PySane_Error(st); if (st) return PySane_Error(st);
switch (p.format) switch (p.format)
{ {
@ -124,8 +124,8 @@ SaneDev_get_parameters(SaneDevObject *self, PyObject *args)
case(SANE_FRAME_GREEN): format="green"; break; case(SANE_FRAME_GREEN): format="green"; break;
case(SANE_FRAME_BLUE): format="blue"; break; case(SANE_FRAME_BLUE): format="blue"; break;
} }
return Py_BuildValue("si(ii)ii", format, p.last_frame, p.pixels_per_line, return Py_BuildValue("si(ii)ii", format, p.last_frame, p.pixels_per_line,
p.lines, p.depth, p.bytes_per_line); p.lines, p.depth, p.bytes_per_line);
} }
@ -135,7 +135,7 @@ SaneDev_fileno(SaneDevObject *self, PyObject *args)
{ {
SANE_Status st; SANE_Status st;
SANE_Int fd; SANE_Int fd;
if (!PyArg_ParseTuple(args, "")) if (!PyArg_ParseTuple(args, ""))
return NULL; return NULL;
if (self->h==NULL) if (self->h==NULL)
@ -152,7 +152,7 @@ static PyObject *
SaneDev_start(SaneDevObject *self, PyObject *args) SaneDev_start(SaneDevObject *self, PyObject *args)
{ {
SANE_Status st; SANE_Status st;
if (!PyArg_ParseTuple(args, "")) if (!PyArg_ParseTuple(args, ""))
return NULL; return NULL;
if (self->h==NULL) if (self->h==NULL)
@ -194,7 +194,7 @@ SaneDev_get_options(SaneDevObject *self, PyObject *args)
const SANE_Option_Descriptor *d; const SANE_Option_Descriptor *d;
PyObject *list, *value; PyObject *list, *value;
int i=1; int i=1;
if (!PyArg_ParseTuple(args, "")) if (!PyArg_ParseTuple(args, ""))
return NULL; return NULL;
if (self->h==NULL) if (self->h==NULL)
@ -205,44 +205,44 @@ SaneDev_get_options(SaneDevObject *self, PyObject *args)
if (!(list = PyList_New(0))) if (!(list = PyList_New(0)))
return NULL; return NULL;
do do
{ {
d=sane_get_option_descriptor(self->h, i); d=sane_get_option_descriptor(self->h, i);
if (d!=NULL) if (d!=NULL)
{ {
PyObject *constraint=NULL; PyObject *constraint=NULL;
int j; int j;
switch (d->constraint_type) switch (d->constraint_type)
{ {
case(SANE_CONSTRAINT_NONE): case(SANE_CONSTRAINT_NONE):
Py_INCREF(Py_None); constraint=Py_None; break; Py_INCREF(Py_None); constraint=Py_None; break;
case(SANE_CONSTRAINT_RANGE): case(SANE_CONSTRAINT_RANGE):
if (d->type == SANE_TYPE_INT) if (d->type == SANE_TYPE_INT)
constraint=Py_BuildValue("iii", d->constraint.range->min, constraint=Py_BuildValue("iii", d->constraint.range->min,
d->constraint.range->max, d->constraint.range->max,
d->constraint.range->quant); d->constraint.range->quant);
else else
constraint=Py_BuildValue("ddd", constraint=Py_BuildValue("ddd",
SANE_UNFIX(d->constraint.range->min), SANE_UNFIX(d->constraint.range->min),
SANE_UNFIX(d->constraint.range->max), SANE_UNFIX(d->constraint.range->max),
SANE_UNFIX(d->constraint.range->quant)); SANE_UNFIX(d->constraint.range->quant));
break; break;
case(SANE_CONSTRAINT_WORD_LIST): case(SANE_CONSTRAINT_WORD_LIST):
constraint=PyList_New(d->constraint.word_list[0]); constraint=PyList_New(d->constraint.word_list[0]);
if (d->type == SANE_TYPE_INT) if (d->type == SANE_TYPE_INT)
for (j=1; j<=d->constraint.word_list[0]; j++) for (j=1; j<=d->constraint.word_list[0]; j++)
PyList_SetItem(constraint, j-1, PyList_SetItem(constraint, j-1,
PyInt_FromLong(d->constraint.word_list[j])); PyInt_FromLong(d->constraint.word_list[j]));
else else
for (j=1; j<=d->constraint.word_list[0]; j++) for (j=1; j<=d->constraint.word_list[0]; j++)
PyList_SetItem(constraint, j-1, PyList_SetItem(constraint, j-1,
PyFloat_FromDouble(SANE_UNFIX(d->constraint.word_list[j]))); PyFloat_FromDouble(SANE_UNFIX(d->constraint.word_list[j])));
break; break;
case(SANE_CONSTRAINT_STRING_LIST): case(SANE_CONSTRAINT_STRING_LIST):
constraint=PyList_New(0); constraint=PyList_New(0);
for(j=0; d->constraint.string_list[j]!=NULL; j++) for(j=0; d->constraint.string_list[j]!=NULL; j++)
PyList_Append(constraint, PyList_Append(constraint,
#if PY_MAJOR_VERSION >= 3 #if PY_MAJOR_VERSION >= 3
PyUnicode_DecodeLatin1(d->constraint.string_list[j], strlen(d->constraint.string_list[j]), NULL)); PyUnicode_DecodeLatin1(d->constraint.string_list[j], strlen(d->constraint.string_list[j]), NULL));
#else #else
@ -250,7 +250,7 @@ SaneDev_get_options(SaneDevObject *self, PyObject *args)
#endif #endif
break; break;
} }
value=Py_BuildValue("isssiiiiO", i, d->name, d->title, d->desc, value=Py_BuildValue("isssiiiiO", i, d->name, d->title, d->desc,
d->type, d->unit, d->size, d->cap, constraint); d->type, d->unit, d->size, d->cap, constraint);
PyList_Append(list, value); PyList_Append(list, value);
} }
@ -267,7 +267,7 @@ SaneDev_get_option(SaneDevObject *self, PyObject *args)
PyObject *value=NULL; PyObject *value=NULL;
int n; int n;
void *v; void *v;
if (!PyArg_ParseTuple(args, "i", &n)) if (!PyArg_ParseTuple(args, "i", &n))
{ {
return NULL; return NULL;
@ -282,12 +282,12 @@ SaneDev_get_option(SaneDevObject *self, PyObject *args)
st=sane_control_option(self->h, n, SANE_ACTION_GET_VALUE, st=sane_control_option(self->h, n, SANE_ACTION_GET_VALUE,
v, NULL); v, NULL);
if (st) if (st)
{ {
free(v); free(v);
return PySane_Error(st); return PySane_Error(st);
} }
switch(d->type) switch(d->type)
{ {
case(SANE_TYPE_BOOL): case(SANE_TYPE_BOOL):
@ -309,7 +309,7 @@ SaneDev_get_option(SaneDevObject *self, PyObject *args)
value=Py_BuildValue("O", Py_None); value=Py_BuildValue("O", Py_None);
break; break;
} }
free(v); free(v);
return value; return value;
} }
@ -323,7 +323,7 @@ SaneDev_set_option(SaneDevObject *self, PyObject *args)
PyObject *value; PyObject *value;
int n; int n;
void *v; void *v;
if (!PyArg_ParseTuple(args, "iO", &n, &value)) if (!PyArg_ParseTuple(args, "iO", &n, &value))
return NULL; return NULL;
if (self->h==NULL) if (self->h==NULL)
@ -337,7 +337,7 @@ SaneDev_set_option(SaneDevObject *self, PyObject *args)
switch(d->type) switch(d->type)
{ {
case(SANE_TYPE_BOOL): case(SANE_TYPE_BOOL):
if (!PyInt_Check(value)) if (!PyInt_Check(value))
{ {
PyErr_SetString(PyExc_TypeError, "SANE_BOOL requires an integer"); PyErr_SetString(PyExc_TypeError, "SANE_BOOL requires an integer");
free(v); free(v);
@ -345,7 +345,7 @@ SaneDev_set_option(SaneDevObject *self, PyObject *args)
} }
/* fall through */ /* fall through */
case(SANE_TYPE_INT): case(SANE_TYPE_INT):
if (!PyInt_Check(value)) if (!PyInt_Check(value))
{ {
PyErr_SetString(PyExc_TypeError, "SANE_INT requires an integer"); PyErr_SetString(PyExc_TypeError, "SANE_INT requires an integer");
free(v); free(v);
@ -354,7 +354,7 @@ SaneDev_set_option(SaneDevObject *self, PyObject *args)
*( (SANE_Int*)v) = PyInt_AsLong(value); *( (SANE_Int*)v) = PyInt_AsLong(value);
break; break;
case(SANE_TYPE_FIXED): case(SANE_TYPE_FIXED):
if (!PyFloat_Check(value)) if (!PyFloat_Check(value))
{ {
PyErr_SetString(PyExc_TypeError, "SANE_FIXED requires a floating point number"); PyErr_SetString(PyExc_TypeError, "SANE_FIXED requires a floating point number");
free(v); free(v);
@ -391,15 +391,15 @@ SaneDev_set_option(SaneDevObject *self, PyObject *args)
((char*)v)[d->size-1] = 0; ((char*)v)[d->size-1] = 0;
#endif #endif
break; break;
case(SANE_TYPE_BUTTON): case(SANE_TYPE_BUTTON):
case(SANE_TYPE_GROUP): case(SANE_TYPE_GROUP):
break; break;
} }
st=sane_control_option(self->h, n, SANE_ACTION_SET_VALUE, st=sane_control_option(self->h, n, SANE_ACTION_SET_VALUE,
v, &i); v, &i);
if (st) {free(v); return PySane_Error(st);} if (st) {free(v); return PySane_Error(st);}
free(v); free(v);
return Py_BuildValue("i", i); return Py_BuildValue("i", i);
} }
@ -410,7 +410,7 @@ SaneDev_set_auto_option(SaneDevObject *self, PyObject *args)
SANE_Status st; SANE_Status st;
SANE_Int i; SANE_Int i;
int n; int n;
if (!PyArg_ParseTuple(args, "i", &n)) if (!PyArg_ParseTuple(args, "i", &n))
return NULL; return NULL;
if (self->h==NULL) if (self->h==NULL)
@ -421,7 +421,7 @@ SaneDev_set_auto_option(SaneDevObject *self, PyObject *args)
st=sane_control_option(self->h, n, SANE_ACTION_SET_AUTO, st=sane_control_option(self->h, n, SANE_ACTION_SET_AUTO,
NULL, &i); NULL, &i);
if (st) {return PySane_Error(st);} if (st) {return PySane_Error(st);}
return Py_BuildValue("i", i); return Py_BuildValue("i", i);
} }
@ -430,7 +430,7 @@ SaneDev_set_auto_option(SaneDevObject *self, PyObject *args)
static PyObject * static PyObject *
SaneDev_snap(SaneDevObject *self, PyObject *args) SaneDev_snap(SaneDevObject *self, PyObject *args)
{ {
SANE_Status st; SANE_Status st;
/* The buffer should be a multiple of 3 in size, so each sane_read /* The buffer should be a multiple of 3 in size, so each sane_read
operation will return an integral number of RGB triples. */ operation will return an integral number of RGB triples. */
SANE_Byte buffer[READSIZE]; /* XXX how big should the buffer be? */ SANE_Byte buffer[READSIZE]; /* XXX how big should the buffer be? */
@ -440,16 +440,16 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
int px, py, remain, cplen, bufpos, padbytes; int px, py, remain, cplen, bufpos, padbytes;
long L; long L;
char errmsg[80]; char errmsg[80];
union union
{ char c[2]; { char c[2];
INT16 i16; INT16 i16;
} }
endian; endian;
PyObject *pyNoCancel = NULL; PyObject *pyNoCancel = NULL;
int noCancel = 0; int noCancel = 0;
endian.i16 = 1; endian.i16 = 1;
if (!PyArg_ParseTuple(args, "l|O", &L, &pyNoCancel)) if (!PyArg_ParseTuple(args, "l|O", &L, &pyNoCancel))
return NULL; return NULL;
if (self->h==NULL) if (self->h==NULL)
@ -458,7 +458,7 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
return NULL; return NULL;
} }
im=(Imaging)L; im=(Imaging)L;
if (pyNoCancel) if (pyNoCancel)
noCancel = PyObject_IsTrue(pyNoCancel); noCancel = PyObject_IsTrue(pyNoCancel);
@ -470,14 +470,14 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
we need to call sane_get_parameters here, and we can create we need to call sane_get_parameters here, and we can create
the result Image object here. the result Image object here.
*/ */
Py_UNBLOCK_THREADS Py_UNBLOCK_THREADS
sane_get_parameters(self->h, &p); sane_get_parameters(self->h, &p);
if (p.format == SANE_FRAME_GRAY) if (p.format == SANE_FRAME_GRAY)
{ {
switch (p.depth) switch (p.depth)
{ {
case 1: case 1:
remain = p.bytes_per_line * im->ysize; remain = p.bytes_per_line * im->ysize;
padbytes = p.bytes_per_line - (im->xsize+7)/8; padbytes = p.bytes_per_line - (im->xsize+7)/8;
bufpos = 0; bufpos = 0;
@ -503,7 +503,7 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
px = 0; px = 0;
} }
} }
st=sane_read(self->h, buffer, st=sane_read(self->h, buffer,
remain<READSIZE ? remain : READSIZE, &len); remain<READSIZE ? remain : READSIZE, &len);
if (st && (st!=SANE_STATUS_EOF)) if (st && (st!=SANE_STATUS_EOF))
{ {
@ -544,7 +544,7 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
} }
bufpos = -len; bufpos = -len;
st=sane_read(self->h, buffer, st=sane_read(self->h, buffer,
remain<READSIZE ? remain : READSIZE, &len); remain<READSIZE ? remain : READSIZE, &len);
if (st && (st!=SANE_STATUS_EOF)) if (st && (st!=SANE_STATUS_EOF))
{ {
@ -576,7 +576,7 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
px = 0; px = 0;
} }
} }
st=sane_read(self->h, buffer, st=sane_read(self->h, buffer,
remain<READSIZE ? remain : READSIZE, &len); remain<READSIZE ? remain : READSIZE, &len);
if (st && (st!=SANE_STATUS_EOF)) if (st && (st!=SANE_STATUS_EOF))
{ {
@ -591,7 +591,7 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
} }
break; break;
default: default:
/* other depths are not formally "illegal" according to the /* other depths are not formally "illegal" according to the
Sane API, but it's agreed by Sane developers that other Sane API, but it's agreed by Sane developers that other
depths than 1, 8, 16 should not be used depths than 1, 8, 16 should not be used
*/ */
@ -607,7 +607,7 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
int incr, color, pxs, pxmax, bit, val, mask; int incr, color, pxs, pxmax, bit, val, mask;
switch (p.depth) switch (p.depth)
{ {
case 1: case 1:
remain = p.bytes_per_line * im->ysize; remain = p.bytes_per_line * im->ysize;
padbytes = p.bytes_per_line - ((im->xsize+7)/8) * 3; padbytes = p.bytes_per_line - ((im->xsize+7)/8) * 3;
bufpos = 0; bufpos = 0;
@ -621,7 +621,7 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
{ {
while (len <= 0 && st == SANE_STATUS_GOOD) while (len <= 0 && st == SANE_STATUS_GOOD)
{ {
st=sane_read(self->h, buffer, st=sane_read(self->h, buffer,
remain<READSIZE ? remain : READSIZE, &len); remain<READSIZE ? remain : READSIZE, &len);
if (st && (st!=SANE_STATUS_EOF)) if (st && (st!=SANE_STATUS_EOF))
{ {
@ -674,7 +674,7 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
bufpos = 0; bufpos = 0;
incr = 1; incr = 1;
} }
else else
{ {
padbytes = p.bytes_per_line - 6 * im->xsize; padbytes = p.bytes_per_line - 6 * im->xsize;
bufpos = endian.c[0]; bufpos = endian.c[0];
@ -689,9 +689,9 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
- we may have padding bytes at the end of a scan line - we may have padding bytes at the end of a scan line
- the number of bytes read with sane_read may be smaller - the number of bytes read with sane_read may be smaller
than the number of pad bytes than the number of pad bytes
- the buffer may become empty after setting any of the - the buffer may become empty after setting any of the
red/green/blue pixel values red/green/blue pixel values
*/ */
while (st != SANE_STATUS_EOF && py < im->ysize) while (st != SANE_STATUS_EOF && py < im->ysize)
{ {
@ -720,7 +720,7 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
len -= bufpos; len -= bufpos;
} }
if (st == SANE_STATUS_EOF) break; if (st == SANE_STATUS_EOF) break;
((UINT8**)(im->image32))[py][px++] = buffer[bufpos]; ((UINT8**)(im->image32))[py][px++] = buffer[bufpos];
bufpos += incr; bufpos += incr;
len -= incr; len -= incr;
} }
@ -744,13 +744,13 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
PyErr_SetString(ErrorObject, errmsg); PyErr_SetString(ErrorObject, errmsg);
return NULL; return NULL;
} }
} }
else /* should be SANE_FRAME_RED, GREEN or BLUE */ else /* should be SANE_FRAME_RED, GREEN or BLUE */
{ {
int lastlen, pxa, pxmax, offset, incr, frame_count = 0; int lastlen, pxa, pxmax, offset, incr, frame_count = 0;
/* at least the Sane test backend behaves a bit weird, if /* at least the Sane test backend behaves a bit weird, if
it returns "premature EOF" for sane_read, i.e., if the it returns "premature EOF" for sane_read, i.e., if the
option "return value of sane_read" is set to SANE_STATUS_EOF. option "return value of sane_read" is set to SANE_STATUS_EOF.
In this case, the test backend does not advance to the next frame, In this case, the test backend does not advance to the next frame,
so p.last_frame will never be set... so p.last_frame will never be set...
@ -772,7 +772,7 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
lastlen = 0; lastlen = 0;
py = 0; py = 0;
switch (p.format) switch (p.format)
{ {
case SANE_FRAME_RED: case SANE_FRAME_RED:
offset = 0; offset = 0;
break; break;
@ -806,14 +806,14 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
mask = 0x80; mask = 0x80;
for (bit = 0; bit < 8 && px < pxmax; bit++) for (bit = 0; bit < 8 && px < pxmax; bit++)
{ {
((UINT8**)(im->image32))[py][px] ((UINT8**)(im->image32))[py][px]
= val&mask ? 0xFF : 0; = val&mask ? 0xFF : 0;
((UINT8**)(im->image32))[py][pxa] = 0; ((UINT8**)(im->image32))[py][pxa] = 0;
px += 4; px += 4;
pxa += 4; pxa += 4;
mask = mask >> 1; mask = mask >> 1;
} }
if (px >= pxmax) if (px >= pxmax)
{ {
px = offset; px = offset;
@ -926,9 +926,9 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
sane_cancel(self->h); sane_cancel(self->h);
return PySane_Error(st); return PySane_Error(st);
} }
st = sane_start(self->h); st = sane_start(self->h);
if (st) if (st)
{ {
Py_BLOCK_THREADS Py_BLOCK_THREADS
return PySane_Error(st); return PySane_Error(st);
@ -947,7 +947,7 @@ SaneDev_snap(SaneDevObject *self, PyObject *args)
Py_BLOCK_THREADS Py_BLOCK_THREADS
return PySane_Error(st); return PySane_Error(st);
} }
if (!noCancel) if (!noCancel)
sane_cancel(self->h); sane_cancel(self->h);
Py_BLOCK_THREADS Py_BLOCK_THREADS
@ -967,7 +967,7 @@ int NUMARRAY_IMPORTED = 0;
static PyObject * static PyObject *
SaneDev_arr_snap(SaneDevObject *self, PyObject *args) SaneDev_arr_snap(SaneDevObject *self, PyObject *args)
{ {
SANE_Status st; SANE_Status st;
SANE_Byte buffer[READSIZE]; SANE_Byte buffer[READSIZE];
SANE_Int len; SANE_Int len;
SANE_Parameters p; SANE_Parameters p;
@ -1035,24 +1035,24 @@ SaneDev_arr_snap(SaneDevObject *self, PyObject *args)
PyErr_SetString(ErrorObject, "failed to create NumArray object"); PyErr_SetString(ErrorObject, "failed to create NumArray object");
return NULL; return NULL;
} }
arr_bytes_per_line = pixels_per_line * bpp; arr_bytes_per_line = pixels_per_line * bpp;
st=SANE_STATUS_GOOD; st=SANE_STATUS_GOOD;
#ifdef WRITE_PGM #ifdef WRITE_PGM
FILE *fp; FILE *fp;
fp = fopen("sane_p5.pgm", "w"); fp = fopen("sane_p5.pgm", "w");
fprintf(fp, "P5\n%d %d\n%d\n", p.pixels_per_line, fprintf(fp, "P5\n%d %d\n%d\n", p.pixels_per_line,
p.lines, (int) pow(2.0, (double) p.depth)-1); p.lines, (int) pow(2.0, (double) p.depth)-1);
#endif #endif
line_index = line = 0; line_index = line = 0;
remain_bytes_line = arr_bytes_per_line; remain_bytes_line = arr_bytes_per_line;
total_remain = p.bytes_per_line * p.lines; total_remain = p.bytes_per_line * p.lines;
num_pad_bytes = p.bytes_per_line - arr_bytes_per_line; num_pad_bytes = p.bytes_per_line - arr_bytes_per_line;
while (st!=SANE_STATUS_EOF) while (st!=SANE_STATUS_EOF)
{ {
Py_BEGIN_ALLOW_THREADS Py_BEGIN_ALLOW_THREADS
st = sane_read(self->h, buffer, st = sane_read(self->h, buffer,
READSIZE < total_remain ? READSIZE : total_remain, &len); READSIZE < total_remain ? READSIZE : total_remain, &len);
Py_END_ALLOW_THREADS Py_END_ALLOW_THREADS
#ifdef WRITE_PGM #ifdef WRITE_PGM
@ -1072,7 +1072,7 @@ SaneDev_arr_snap(SaneDevObject *self, PyObject *args)
len -= cp_num_bytes; len -= cp_num_bytes;
#ifdef DEBUG #ifdef DEBUG
printf("copying %d bytes from b_idx %d to d_idx %d\n", printf("copying %d bytes from b_idx %d to d_idx %d\n",
cp_num_bytes, buffer_index, cp_num_bytes, buffer_index,
line * arr_bytes_per_line + line_index); line * arr_bytes_per_line + line_index);
printf("len is now %d\n", len); printf("len is now %d\n", len);
#endif #endif
@ -1090,7 +1090,7 @@ SaneDev_arr_snap(SaneDevObject *self, PyObject *args)
remain_bytes_line = arr_bytes_per_line; remain_bytes_line = arr_bytes_per_line;
line++; line++;
line_index = 0; line_index = 0;
/* Skip the number of bytes in the input stream which /* Skip the number of bytes in the input stream which
are not used: */ are not used: */
len -= num_pad_bytes; len -= num_pad_bytes;
buffer_index += num_pad_bytes; buffer_index += num_pad_bytes;
@ -1171,12 +1171,12 @@ PySane_init(PyObject *self, PyObject *args)
{ {
SANE_Status st; SANE_Status st;
SANE_Int version; SANE_Int version;
if (!PyArg_ParseTuple(args, "")) if (!PyArg_ParseTuple(args, ""))
return NULL; return NULL;
/* XXX Authorization is not yet supported */ /* XXX Authorization is not yet supported */
st=sane_init(&version, NULL); st=sane_init(&version, NULL);
if (st) return PySane_Error(st); if (st) return PySane_Error(st);
return Py_BuildValue("iiii", version, SANE_VERSION_MAJOR(version), return Py_BuildValue("iiii", version, SANE_VERSION_MAJOR(version),
SANE_VERSION_MINOR(version), SANE_VERSION_BUILD(version)); SANE_VERSION_MINOR(version), SANE_VERSION_BUILD(version));
@ -1201,12 +1201,12 @@ PySane_get_devices(PyObject *self, PyObject *args)
SANE_Status st; SANE_Status st;
PyObject *list; PyObject *list;
int local_only = 0, i; int local_only = 0, i;
if (!PyArg_ParseTuple(args, "|i", &local_only)) if (!PyArg_ParseTuple(args, "|i", &local_only))
{ {
return NULL; return NULL;
} }
Py_BEGIN_ALLOW_THREADS Py_BEGIN_ALLOW_THREADS
st=sane_get_devices(&devlist, local_only); st=sane_get_devices(&devlist, local_only);
Py_END_ALLOW_THREADS Py_END_ALLOW_THREADS
@ -1216,10 +1216,10 @@ PySane_get_devices(PyObject *self, PyObject *args)
for(i=0; devlist[i]!=NULL; i++) for(i=0; devlist[i]!=NULL; i++)
{ {
dev=devlist[i]; dev=devlist[i];
PyList_Append(list, Py_BuildValue("ssss", dev->name, dev->vendor, PyList_Append(list, Py_BuildValue("ssss", dev->name, dev->vendor,
dev->model, dev->type)); dev->model, dev->type));
} }
return list; return list;
} }
@ -1240,7 +1240,7 @@ PySane_open(PyObject *self, PyObject *args)
Py_BEGIN_ALLOW_THREADS Py_BEGIN_ALLOW_THREADS
st = sane_open(name, &(rv->h)); st = sane_open(name, &(rv->h));
Py_END_ALLOW_THREADS Py_END_ALLOW_THREADS
if (st) if (st)
{ {
Py_DECREF(rv); Py_DECREF(rv);
return PySane_Error(st); return PySane_Error(st);
@ -1253,7 +1253,7 @@ PySane_OPTION_IS_ACTIVE(PyObject *self, PyObject *args)
{ {
SANE_Int cap; SANE_Int cap;
long lg; long lg;
if (!PyArg_ParseTuple(args, "l", &lg)) if (!PyArg_ParseTuple(args, "l", &lg))
return NULL; return NULL;
cap=lg; cap=lg;
@ -1265,7 +1265,7 @@ PySane_OPTION_IS_SETTABLE(PyObject *self, PyObject *args)
{ {
SANE_Int cap; SANE_Int cap;
long lg; long lg;
if (!PyArg_ParseTuple(args, "l", &lg)) if (!PyArg_ParseTuple(args, "l", &lg))
return NULL; return NULL;
cap=lg; cap=lg;
@ -1377,7 +1377,7 @@ init_sane(void)
insint(d, "INFO_INEXACT", SANE_INFO_INEXACT); insint(d, "INFO_INEXACT", SANE_INFO_INEXACT);
insint(d, "INFO_RELOAD_OPTIONS", SANE_INFO_RELOAD_OPTIONS); insint(d, "INFO_RELOAD_OPTIONS", SANE_INFO_RELOAD_OPTIONS);
insint(d, "INFO_RELOAD_PARAMS", SANE_INFO_RELOAD_PARAMS); insint(d, "INFO_RELOAD_PARAMS", SANE_INFO_RELOAD_PARAMS);
/* Check for errors */ /* Check for errors */
if (PyErr_Occurred()) if (PyErr_Occurred())
Py_FatalError("can't initialize module _sane"); Py_FatalError("can't initialize module _sane");
@ -1387,7 +1387,7 @@ init_sane(void)
if (PyErr_Occurred()) if (PyErr_Occurred())
PyErr_Clear(); PyErr_Clear();
else else
/* this global variable is declared just in front of the /* this global variable is declared just in front of the
arr_snap() function and should be set to 1 after arr_snap() function and should be set to 1 after
successfully importing the numarray module. */ successfully importing the numarray module. */
NUMARRAY_IMPORTED = 1; NUMARRAY_IMPORTED = 1;

View File

@ -9,13 +9,13 @@ understanding.
This module has been originally developed by A.M. Kuchling (amk1@erols.com), This module has been originally developed by A.M. Kuchling (amk1@erols.com),
now development has been taken over by Ralph Heinkel (rheinkel-at-email.de). now development has been taken over by Ralph Heinkel (rheinkel-at-email.de).
If you write to me please make sure to have the word 'SANE' or 'sane' in If you write to me please make sure to have the word 'SANE' or 'sane' in
the subject of your mail, otherwise it might be classified as spam in the the subject of your mail, otherwise it might be classified as spam in the
future. future.
The module exports two object types, a bunch of constants, and two The module exports two object types, a bunch of constants, and two
functions. functions.
get_devices() get_devices()
Return a list of 4-tuples containing the available scanning Return a list of 4-tuples containing the available scanning
@ -73,7 +73,7 @@ get_parameters()
start() start()
Start a scan. This function must be called before the Start a scan. This function must be called before the
_snap()_ method can be used. _snap()_ method can be used.
cancel() cancel()
Cancel a scan already in progress. Cancel a scan already in progress.
@ -81,7 +81,7 @@ snap(no_cancel=0)
Snap a single frame of data, returning a PIL Image object Snap a single frame of data, returning a PIL Image object
containing the data. If no_cancel is false, the Sane library function containing the data. If no_cancel is false, the Sane library function
sane_cancel is called after the scan. This is reasonable in most cases, sane_cancel is called after the scan. This is reasonable in most cases,
but may cause backends for duplex ADF scanners to drop the backside image, but may cause backends for duplex ADF scanners to drop the backside image,
when snap() is called for the front side image. If no_cancel is true, when snap() is called for the front side image. If no_cancel is true,
cancel() should be called manually, after all scans are finished. cancel() should be called manually, after all scans are finished.
@ -90,13 +90,13 @@ scan()
Returns a PIL image Returns a PIL image
multi_scan() multi_scan()
This method returns an iterator. It is intended to be used for This method returns an iterator. It is intended to be used for
scanning with an automatic document feeder. The next() method of the scanning with an automatic document feeder. The next() method of the
iterator tries to start a scan. If this is successful, it returns a iterator tries to start a scan. If this is successful, it returns a
PIL Image object, like scan(); if the document feeder runs out of PIL Image object, like scan(); if the document feeder runs out of
paper, it raises StopIteration, thereby signaling that the sequence paper, it raises StopIteration, thereby signaling that the sequence
is ran out of items. is ran out of items.
arr_snap(multipleOf=1) arr_snap(multipleOf=1)
same as snap, but the result is a NumArray object. (Not that same as snap, but the result is a NumArray object. (Not that
num_array must be installed already at compilation time, otherwise num_array must be installed already at compilation time, otherwise
@ -123,14 +123,14 @@ Attributes:
SaneDev objects have a few fixed attributes which are always SaneDev objects have a few fixed attributes which are always
available, and a larger collection of attributes which vary depending available, and a larger collection of attributes which vary depending
on the device. An Epson 1660 photo scanner has attributes like on the device. An Epson 1660 photo scanner has attributes like
'mode', 'depth', etc. 'mode', 'depth', etc.
Another (pseudo scanner), the _pnm:0_ device, takes a PNM file and Another (pseudo scanner), the _pnm:0_ device, takes a PNM file and
simulates a scanner using the image data; a SaneDev object simulates a scanner using the image data; a SaneDev object
representing the _pnm:0_ device therefore has a _filename_ attribute representing the _pnm:0_ device therefore has a _filename_ attribute
which can be changed to specify the filename, _contrast_ and which can be changed to specify the filename, _contrast_ and
_brightness_ attributes to modify the returned image, and so forth. _brightness_ attributes to modify the returned image, and so forth.
The values of the scanner options may be an integer, floating-point The values of the scanner options may be an integer, floating-point
value, or string, depending on the nature of the option. value, or string, depending on the nature of the option.
sane_signature sane_signature
@ -183,13 +183,13 @@ In order to change 'mode' to 'gray', just type:
>>> s.mode = 'gray' >>> s.mode = 'gray'
With the attributes and methods of sane-option objects it is possible With the attributes and methods of sane-option objects it is possible
to access individual option values: to access individual option values:
is_active() is_active()
Returns true if the option is active. Returns true if the option is active.
is_settable() is_settable()
Returns true if the option can be set under software control. Returns true if the option can be set under software control.
@ -216,21 +216,21 @@ index
An integer giving the option's index in the option list. An integer giving the option's index in the option list.
name name
A short name for the option, as it comes from the sane-backend. A short name for the option, as it comes from the sane-backend.
py_name py_name
The option's name, as a legal Python identifier. The name The option's name, as a legal Python identifier. The name
attribute may contain the '-' character, so it will be converted to attribute may contain the '-' character, so it will be converted to
'_' for the py_name attribute. '_' for the py_name attribute.
size size
For a string-valued option, this is the maximum length allowed. For a string-valued option, this is the maximum length allowed.
title title
A single-line string that can be used as a title string. A single-line string that can be used as a title string.
type type
A constant giving the type of this option: will be one of the following A constant giving the type of this option: will be one of the following
constants found in the SANE module: constants found in the SANE module:
TYPE_BOOL TYPE_BOOL
TYPE_INT TYPE_INT
@ -274,7 +274,7 @@ Device parameters: ('L', 1, (424, 585), 1, 53)
## In order to obtain a 16-bit grayscale image at 100DPI in a numarray object ## In order to obtain a 16-bit grayscale image at 100DPI in a numarray object
## with bottom-right coordinates set to (160, 120) [in millimeter] : ## with bottom-right coordinates set to (160, 120) [in millimeter] :
>>> s.mode = 'gray' >>> s.mode = 'gray'
>>> s.br_x=160. ; s.br_y=120. >>> s.br_x=160. ; s.br_y=120.
>>> s.resolution = 100 >>> s.resolution = 100
>>> s.depth=16 >>> s.depth=16
>>> s.start() >>> s.start()

View File

@ -30,7 +30,7 @@ OUTMODE = "RGB"
PROOF_PROFILE = "c:\\temp\\profiles\\monitor.icm" PROOF_PROFILE = "c:\\temp\\profiles\\monitor.icm"
# set to True to show() images, False to save them into OUTPUT_DIRECTORY # set to True to show() images, False to save them into OUTPUT_DIRECTORY
SHOW = False SHOW = False
# Tests you can enable/disable # Tests you can enable/disable
TEST_error_catching = True TEST_error_catching = True
@ -63,9 +63,9 @@ if TEST_error_catching == True:
#neither of these proifles exists (unless you make them), so we should #neither of these proifles exists (unless you make them), so we should
# get an error # get an error
imOut = ImageCms.profileToProfile(im, "missingProfile.icm", "cmyk.icm") imOut = ImageCms.profileToProfile(im, "missingProfile.icm", "cmyk.icm")
except PyCMSError as reason: except PyCMSError as reason:
print("We caught a PyCMSError: %s\n\n" %reason) print("We caught a PyCMSError: %s\n\n" %reason)
print("error catching test completed successfully (if you see the message \ print("error catching test completed successfully (if you see the message \
above that we caught the error).") above that we caught the error).")
@ -75,21 +75,21 @@ if TEST_profileToProfile == True:
im = Image.open(IMAGE) im = Image.open(IMAGE)
# send the image, input/output profiles, and rendering intent to # send the image, input/output profiles, and rendering intent to
# ImageCms.profileToProfile() # ImageCms.profileToProfile()
imOut = ImageCms.profileToProfile(im, INPUT_PROFILE, OUTPUT_PROFILE, \ imOut = ImageCms.profileToProfile(im, INPUT_PROFILE, OUTPUT_PROFILE, \
outputMode = OUTMODE) outputMode = OUTMODE)
# now that the image is converted, save or display it # now that the image is converted, save or display it
outputImage(imOut, "profileToProfile") outputImage(imOut, "profileToProfile")
print("profileToProfile test completed successfully.") print("profileToProfile test completed successfully.")
if TEST_profileToProfile_inPlace == True: if TEST_profileToProfile_inPlace == True:
# we'll do the same test as profileToProfile, but modify im in place # we'll do the same test as profileToProfile, but modify im in place
# instead of getting a new image returned to us # instead of getting a new image returned to us
im = Image.open(IMAGE) im = Image.open(IMAGE)
# send the image to ImageCms.profileToProfile(), specifying inPlace = True # send the image to ImageCms.profileToProfile(), specifying inPlace = True
result = ImageCms.profileToProfile(im, INPUT_PROFILE, OUTPUT_PROFILE, \ result = ImageCms.profileToProfile(im, INPUT_PROFILE, OUTPUT_PROFILE, \
outputMode = OUTMODE, inPlace = True) outputMode = OUTMODE, inPlace = True)
@ -117,7 +117,7 @@ if TEST_buildTransform == True:
# then transform it again using the same transform, this time in-place. # then transform it again using the same transform, this time in-place.
result = ImageCms.applyTransform(im, transform, inPlace = True) result = ImageCms.applyTransform(im, transform, inPlace = True)
outputImage(im, "buildTransform_inPlace") outputImage(im, "buildTransform_inPlace")
print("buildTransform test completed successfully.") print("buildTransform test completed successfully.")
@ -149,10 +149,10 @@ if TEST_buildTransformFromOpenProfiles == True:
# then do it again using the same transform, this time in-place. # then do it again using the same transform, this time in-place.
result = ImageCms.applyTransform(im, transform, inPlace = True) result = ImageCms.applyTransform(im, transform, inPlace = True)
outputImage(im, "buildTransformFromOpenProfiles_inPlace") outputImage(im, "buildTransformFromOpenProfiles_inPlace")
print("buildTransformFromOpenProfiles test completed successfully.") print("buildTransformFromOpenProfiles test completed successfully.")
# and, to clean up a bit, delete the transform # and, to clean up a bit, delete the transform
# this should call the C destructor for the each item. # this should call the C destructor for the each item.
# Python should also do this automatically when it goes out of scope. # Python should also do this automatically when it goes out of scope.
@ -179,7 +179,7 @@ if TEST_buildProofTransform == True:
# then transform it again using the same transform, this time in-place. # then transform it again using the same transform, this time in-place.
result = ImageCms.applyTransform(im, transform, inPlace = True) result = ImageCms.applyTransform(im, transform, inPlace = True)
outputImage(im, "buildProofTransform_inPlace") outputImage(im, "buildProofTransform_inPlace")
print("buildProofTransform test completed successfully.") print("buildProofTransform test completed successfully.")
@ -187,11 +187,11 @@ if TEST_buildProofTransform == True:
# this should call the C destructor for the transform structure. # this should call the C destructor for the transform structure.
# Python should also do this automatically when it goes out of scope. # Python should also do this automatically when it goes out of scope.
del(transform) del(transform)
if TEST_getProfileInfo == True: if TEST_getProfileInfo == True:
# get a profile handle # get a profile handle
profile = ImageCms.getOpenProfile(INPUT_PROFILE) profile = ImageCms.getOpenProfile(INPUT_PROFILE)
# lets print some info about our input profile: # lets print some info about our input profile:
print("Profile name (retrieved from profile string path name): %s" %ImageCms.getProfileName(INPUT_PROFILE)) print("Profile name (retrieved from profile string path name): %s" %ImageCms.getProfileName(INPUT_PROFILE))
@ -208,7 +208,7 @@ if TEST_getProfileInfo == True:
# Hmmmm... but does this profile support INTENT_ABSOLUTE_COLORIMETRIC? # Hmmmm... but does this profile support INTENT_ABSOLUTE_COLORIMETRIC?
print("Does it support INTENT_ABSOLUTE_COLORIMETRIC?: (1 is yes, -1 is no): %s" \ print("Does it support INTENT_ABSOLUTE_COLORIMETRIC?: (1 is yes, -1 is no): %s" \
%ImageCms.isIntentSupported(profile, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC, \ %ImageCms.isIntentSupported(profile, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC, \
ImageCms.DIRECTION_INPUT)) ImageCms.DIRECTION_INPUT))
print("getProfileInfo test completed successfully.") print("getProfileInfo test completed successfully.")
@ -219,4 +219,4 @@ if TEST_misc == True:
print("Copyright:\n\n%s" %ImageCms.copyright()) print("Copyright:\n\n%s" %ImageCms.copyright())
print("misc test completed successfully.") print("misc test completed successfully.")

View File

@ -46,7 +46,7 @@ for i0 in range(65556):
min_size = size min_size = size
min_start = i0 min_start = i0
print() print()
# print check(min_size, min_start) # print check(min_size, min_start)

View File

@ -22,7 +22,7 @@ def _assert_noerr(im):
print("No _compression") print("No _compression")
print (dir(im)) print (dir(im))
# can we write it back out, in a different form. # can we write it back out, in a different form.
out = tempfile("temp.png") out = tempfile("temp.png")
assert_no_exception(lambda: im.save(out)) assert_no_exception(lambda: im.save(out))
@ -62,7 +62,7 @@ def test_g4_tiff_bytesio():
assert_equal(im.size, (500,500)) assert_equal(im.size, (500,500))
_assert_noerr(im) _assert_noerr(im)
def test_g4_eq_png(): def test_g4_eq_png():
""" Checking that we're actually getting the data that we expect""" """ Checking that we're actually getting the data that we expect"""
png = Image.open('Tests/images/lena_bw_500.png') png = Image.open('Tests/images/lena_bw_500.png')

View File

@ -8,7 +8,7 @@ codecs = dir(Image.core)
if "group4_encoder" not in codecs or "group4_decoder" not in codecs: if "group4_encoder" not in codecs or "group4_decoder" not in codecs:
skip("tiff support not available") skip("tiff support not available")
""" The small lena image was failing on open in the libtiff """ The small lena image was failing on open in the libtiff
decoder because the file pointer was set to the wrong place decoder because the file pointer was set to the wrong place
by a spurious seek. It wasn't failing with the byteio method. by a spurious seek. It wasn't failing with the byteio method.
@ -18,7 +18,7 @@ if "group4_encoder" not in codecs or "group4_decoder" not in codecs:
to ensure that it stays fixed. """ to ensure that it stays fixed. """
def test_g4_lena_file(): def test_g4_lena_file():
"""Testing the open file load path""" """Testing the open file load path"""
file = "Tests/images/lena_g4.tif" file = "Tests/images/lena_g4.tif"
@ -28,7 +28,7 @@ def test_g4_lena_file():
assert_equal(im.size, (128,128)) assert_equal(im.size, (128,128))
_assert_noerr(im) _assert_noerr(im)
def test_g4_lena_bytesio(): def test_g4_lena_bytesio():
"""Testing the bytesio loading code path""" """Testing the bytesio loading code path"""
from io import BytesIO from io import BytesIO
file = "Tests/images/lena_g4.tif" file = "Tests/images/lena_g4.tif"
@ -40,8 +40,8 @@ def test_g4_lena_bytesio():
assert_equal(im.size, (128,128)) assert_equal(im.size, (128,128))
_assert_noerr(im) _assert_noerr(im)
def test_g4_lena(): def test_g4_lena():
"""The 128x128 lena image fails for some reason. Investigating""" """The 128x128 lena image fails for some reason. Investigating"""
file = "Tests/images/lena_g4.tif" file = "Tests/images/lena_g4.tif"
@ -49,4 +49,4 @@ def test_g4_lena():
assert_equal(im.size, (128,128)) assert_equal(im.size, (128,128))
_assert_noerr(im) _assert_noerr(im)

View File

@ -13,68 +13,68 @@ def test_version():
def test_good_alpha(): def test_good_alpha():
assert_equal(_webp.WebPDecoderBuggyAlpha(), 0) assert_equal(_webp.WebPDecoderBuggyAlpha(), 0)
def test_read_rgb(): def test_read_rgb():
file_path = "Images/lena.webp" file_path = "Images/lena.webp"
image = Image.open(file_path) image = Image.open(file_path)
assert_equal(image.mode, "RGB") assert_equal(image.mode, "RGB")
assert_equal(image.size, (128, 128)) assert_equal(image.size, (128, 128))
assert_equal(image.format, "WEBP") assert_equal(image.format, "WEBP")
assert_no_exception(lambda: image.load()) assert_no_exception(lambda: image.load())
assert_no_exception(lambda: image.getdata()) assert_no_exception(lambda: image.getdata())
# generated with: dwebp -ppm ../../Images/lena.webp -o lena_webp_bits.ppm # generated with: dwebp -ppm ../../Images/lena.webp -o lena_webp_bits.ppm
target = Image.open('Tests/images/lena_webp_bits.ppm') target = Image.open('Tests/images/lena_webp_bits.ppm')
assert_image_equal(image, target) assert_image_equal(image, target)
def test_write_rgb(): def test_write_rgb():
""" """
Can we write a RGB mode file to webp without error. Does it have the bits we Can we write a RGB mode file to webp without error. Does it have the bits we
expect? expect?
""" """
temp_file = tempfile("temp.webp") temp_file = tempfile("temp.webp")
lena("RGB").save(temp_file) lena("RGB").save(temp_file)
image = Image.open(temp_file) image = Image.open(temp_file)
image.load() image.load()
assert_equal(image.mode, "RGB") assert_equal(image.mode, "RGB")
assert_equal(image.size, (128, 128)) assert_equal(image.size, (128, 128))
assert_equal(image.format, "WEBP") assert_equal(image.format, "WEBP")
assert_no_exception(lambda: image.load()) assert_no_exception(lambda: image.load())
assert_no_exception(lambda: image.getdata()) assert_no_exception(lambda: image.getdata())
# If we're using the exact same version of webp, this test should pass. # If we're using the exact same version of webp, this test should pass.
# but it doesn't if the webp is generated on Ubuntu and tested on Fedora. # but it doesn't if the webp is generated on Ubuntu and tested on Fedora.
# generated with: dwebp -ppm temp.webp -o lena_webp_write.ppm # generated with: dwebp -ppm temp.webp -o lena_webp_write.ppm
#target = Image.open('Tests/images/lena_webp_write.ppm') #target = Image.open('Tests/images/lena_webp_write.ppm')
#assert_image_equal(image, target) #assert_image_equal(image, target)
# This test asserts that the images are similar. If the average pixel difference # This test asserts that the images are similar. If the average pixel difference
# between the two images is less than the epsilon value, then we're going to # between the two images is less than the epsilon value, then we're going to
# accept that it's a reasonable lossy version of the image. The included lena images # accept that it's a reasonable lossy version of the image. The included lena images
# for webp are showing ~16 on Ubuntu, the jpegs are showing ~18. # for webp are showing ~16 on Ubuntu, the jpegs are showing ~18.
target = lena("RGB") target = lena("RGB")
assert_image_similar(image, target, 20.0) assert_image_similar(image, target, 20.0)
def test_write_rgba(): def test_write_rgba():
""" """
Can we write a RGBA mode file to webp without error. Does it have the bits we Can we write a RGBA mode file to webp without error. Does it have the bits we
expect? expect?
""" """
temp_file = tempfile("temp.webp") temp_file = tempfile("temp.webp")
pil_image = Image.new("RGBA", (10, 10), (255, 0, 0, 20)) pil_image = Image.new("RGBA", (10, 10), (255, 0, 0, 20))
pil_image.save(temp_file) pil_image.save(temp_file)
@ -83,13 +83,13 @@ def test_write_rgba():
image = Image.open(temp_file) image = Image.open(temp_file)
image.load() image.load()
assert_equal(image.mode, "RGBA") assert_equal(image.mode, "RGBA")
assert_equal(image.size, (10, 10)) assert_equal(image.size, (10, 10))
assert_equal(image.format, "WEBP") assert_equal(image.format, "WEBP")
assert_no_exception(image.load) assert_no_exception(image.load)
assert_no_exception(image.getdata) assert_no_exception(image.getdata)
assert_image_similar(image, pil_image, 1.0) assert_image_similar(image, pil_image, 1.0)
if _webp.WebPDecoderBuggyAlpha(): if _webp.WebPDecoderBuggyAlpha():
@ -99,15 +99,15 @@ def test_read_rgba():
# Generated with `cwebp transparent.png -o transparent.webp` # Generated with `cwebp transparent.png -o transparent.webp`
file_path = "Images/transparent.webp" file_path = "Images/transparent.webp"
image = Image.open(file_path) image = Image.open(file_path)
assert_equal(image.mode, "RGBA") assert_equal(image.mode, "RGBA")
assert_equal(image.size, (200, 150)) assert_equal(image.size, (200, 150))
assert_equal(image.format, "WEBP") assert_equal(image.format, "WEBP")
assert_no_exception(lambda: image.load()) assert_no_exception(lambda: image.load())
assert_no_exception(lambda: image.getdata()) assert_no_exception(lambda: image.getdata())
orig_bytes = image.tobytes() orig_bytes = image.tobytes()
target = Image.open('Images/transparent.png') target = Image.open('Images/transparent.png')
assert_image_similar(image, target, 20.0) assert_image_similar(image, target, 20.0)

View File

@ -30,7 +30,7 @@ def test_internals():
im.readonly = 1 im.readonly = 1
im._copy() im._copy()
assert_false(im.readonly) assert_false(im.readonly)
im.readonly = 1 im.readonly = 1
im.paste(0, (0, 0, 100, 100)) im.paste(0, (0, 0, 100, 100))
assert_false(im.readonly) assert_false(im.readonly)

View File

@ -31,7 +31,7 @@ def test_sanity():
def test_crash(): def test_crash():
# crashes on small images # crashes on small images
im = Image.new("RGB", (1, 1)) im = Image.new("RGB", (1, 1))
assert_no_exception(lambda: im.filter(ImageFilter.SMOOTH)) assert_no_exception(lambda: im.filter(ImageFilter.SMOOTH))

View File

@ -10,7 +10,7 @@ def color(mode):
return tuple(range(1, bands+1)) return tuple(range(1, bands+1))
def test_pixel(): def test_pixel():
def pixel(mode): def pixel(mode):
c = color(mode) c = color(mode)
im = Image.new(mode, (1, 1), None) im = Image.new(mode, (1, 1), None)
@ -33,7 +33,7 @@ def test_pixel():
assert_equal(pixel("YCbCr"), (1, 2, 3)) assert_equal(pixel("YCbCr"), (1, 2, 3))
def test_image(): def test_image():
def pixel(mode): def pixel(mode):
im = Image.new(mode, (1, 1), color(mode)) im = Image.new(mode, (1, 1), color(mode))
return im.getpixel((0, 0)) return im.getpixel((0, 0))
@ -54,4 +54,4 @@ def test_image():
assert_equal(pixel("YCbCr"), (1, 2, 3)) assert_equal(pixel("YCbCr"), (1, 2, 3))

View File

@ -3,7 +3,7 @@ from tester import *
from PIL import Image from PIL import Image
def test_sanity(): def test_sanity():
im = lena() im = lena()
assert_no_exception(lambda: im.mode) assert_no_exception(lambda: im.mode)

View File

@ -3,7 +3,7 @@ from tester import *
from PIL import Image from PIL import Image
def test_offset(): def test_offset():
im1 = lena() im1 = lena()
im2 = assert_warning(DeprecationWarning, lambda: im1.offset(10)) im2 = assert_warning(DeprecationWarning, lambda: im1.offset(10))

View File

@ -3,7 +3,7 @@ from tester import *
from PIL import Image from PIL import Image
def test_sanity(): def test_sanity():
im = lena() im = lena()
assert_exception(ValueError, lambda: im.point(list(range(256)))) assert_exception(ValueError, lambda: im.point(list(range(256))))

View File

@ -11,7 +11,7 @@ def test_sanity():
for x in range(im1.size[0]): for x in range(im1.size[0]):
pos = x, y pos = x, y
im2.putpixel(pos, im1.getpixel(pos)) im2.putpixel(pos, im1.getpixel(pos))
assert_image_equal(im1, im2) assert_image_equal(im1, im2)
im2 = Image.new(im1.mode, im1.size, 0) im2 = Image.new(im1.mode, im1.size, 0)
@ -21,7 +21,7 @@ def test_sanity():
for x in range(im1.size[0]): for x in range(im1.size[0]):
pos = x, y pos = x, y
im2.putpixel(pos, im1.getpixel(pos)) im2.putpixel(pos, im1.getpixel(pos))
assert_false(im2.readonly) assert_false(im2.readonly)
assert_image_equal(im1, im2) assert_image_equal(im1, im2)

View File

@ -12,7 +12,7 @@ def test_sanity():
im = lena() im = lena()
im = im.quantize(palette=lena("P")) im = im.quantize(palette=lena("P"))
assert_image(im, "P", im.size) assert_image(im, "P", im.size)
def test_octree_quantize(): def test_octree_quantize():
im = lena() im = lena()

View File

@ -3,7 +3,7 @@ from tester import *
from PIL import Image from PIL import Image
def test_sanity(): def test_sanity():
assert_exception(ValueError, lambda: lena().tobitmap()) assert_exception(ValueError, lambda: lena().tobitmap())
assert_no_exception(lambda: lena().convert("1").tobitmap()) assert_no_exception(lambda: lena().convert("1").tobitmap())

View File

@ -31,4 +31,4 @@ def test_roundtrip():
assert_image_equal(im, transpose(ROTATE_90, ROTATE_270)) assert_image_equal(im, transpose(ROTATE_90, ROTATE_270))
assert_image_equal(im, transpose(ROTATE_180, ROTATE_180)) assert_image_equal(im, transpose(ROTATE_180, ROTATE_180))

View File

@ -18,7 +18,7 @@ def test_sanity():
success() success()
def test_deprecated(): def test_deprecated():
im = lena().copy() im = lena().copy()
draw = ImageDraw.Draw(im) draw = ImageDraw.Draw(im)

View File

@ -67,5 +67,5 @@ def test_safeblock():
im2 = fromstring(tostring(im1, "PNG")) im2 = fromstring(tostring(im1, "PNG"))
finally: finally:
ImageFile.SAFEBLOCK = SAFEBLOCK ImageFile.SAFEBLOCK = SAFEBLOCK
assert_image_equal(im1, im2) assert_image_equal(im1, im2)

View File

@ -21,4 +21,4 @@ def test_fileio():
im2 = Image.open(io) im2 = Image.open(io)
assert_image_equal(im1, im2) assert_image_equal(im1, im2)

View File

@ -25,7 +25,7 @@ def _font_as_bytes():
with open(font_path, 'rb') as f: with open(font_path, 'rb') as f:
font_bytes = BytesIO(f.read()) font_bytes = BytesIO(f.read())
return font_bytes return font_bytes
def test_font_with_filelike(): def test_font_with_filelike():
assert_no_exception(lambda: ImageFont.truetype(_font_as_bytes(), font_size)) assert_no_exception(lambda: ImageFont.truetype(_font_as_bytes(), font_size))
assert_no_exception(lambda: _render(_font_as_bytes())) assert_no_exception(lambda: _render(_font_as_bytes()))
@ -37,7 +37,7 @@ def test_font_with_filelike():
def test_font_with_open_file(): def test_font_with_open_file():
with open(font_path, 'rb') as f: with open(font_path, 'rb') as f:
assert_no_exception(lambda: _render(f)) assert_no_exception(lambda: _render(f))
def test_font_old_parameters(): def test_font_old_parameters():
assert_warning(DeprecationWarning, lambda: ImageFont.truetype(filename=font_path, size=font_size)) assert_warning(DeprecationWarning, lambda: ImageFont.truetype(filename=font_path, size=font_size))

View File

@ -28,7 +28,7 @@ def test_file():
file = tempfile("temp.lut") file = tempfile("temp.lut")
palette.save(file) palette.save(file)
from PIL.ImagePalette import load, raw from PIL.ImagePalette import load, raw
p = load(file) p = load(file)
@ -40,5 +40,5 @@ def test_file():
p = raw(p[1], p[0]) p = raw(p[1], p[0])
assert_true(isinstance(p, ImagePalette)) assert_true(isinstance(p, ImagePalette))

View File

@ -9,9 +9,9 @@ def test_sanity():
im = lena("RGB") im = lena("RGB")
im.save(file) im.save(file)
seq = ImageSequence.Iterator(im) seq = ImageSequence.Iterator(im)
index = 0 index = 0
for frame in seq: for frame in seq:
assert_image_equal(im, frame) assert_image_equal(im, frame)

View File

@ -1,10 +1,10 @@
from __future__ import print_function from __future__ import print_function
# require that deprecation warnings are triggered # require that deprecation warnings are triggered
import warnings import warnings
warnings.simplefilter('default') warnings.simplefilter('default')
# temporarily turn off resource warnings that warn about unclosed # temporarily turn off resource warnings that warn about unclosed
# files in the test scripts. # files in the test scripts.
try: try:
warnings.filterwarnings("ignore", category=ResourceWarning) warnings.filterwarnings("ignore", category=ResourceWarning)
except NameError: except NameError:

View File

@ -1,5 +1,5 @@
==================================================================== ====================================================================
Using PIL With Tkinter Using PIL With Tkinter
==================================================================== ====================================================================
Starting with 1.0 final (release candidate 2 and later, to be Starting with 1.0 final (release candidate 2 and later, to be

View File

@ -11,11 +11,11 @@
* *
* To use this module, import the _imagingtk module (ImageTk does * To use this module, import the _imagingtk module (ImageTk does
* this for you). * this for you).
* *
* If you're using Python in an embedded context, you can add the * If you're using Python in an embedded context, you can add the
* following lines to your Tcl_AppInit function (in tkappinit.c) * following lines to your Tcl_AppInit function (in tkappinit.c)
* instead. Put them after the calls to Tcl_Init and Tk_Init: * instead. Put them after the calls to Tcl_Init and Tk_Init:
* *
* { * {
* extern void TkImaging_Init(Tcl_Interp* interp); * extern void TkImaging_Init(Tcl_Interp* interp);
* TkImaging_Init(interp); * TkImaging_Init(interp);

View File

@ -1,4 +1,4 @@
/* /*
* pyCMS * pyCMS
* a Python / PIL interface to the littleCMS ICC Color Management System * a Python / PIL interface to the littleCMS ICC Color Management System
* Copyright (C) 2002-2003 Kevin Cazabon * Copyright (C) 2002-2003 Kevin Cazabon
@ -6,11 +6,11 @@
* http://www.cazabon.com * http://www.cazabon.com
* Adapted/reworked for PIL by Fredrik Lundh * Adapted/reworked for PIL by Fredrik Lundh
* Copyright (c) 2009 Fredrik Lundh * Copyright (c) 2009 Fredrik Lundh
* *
* pyCMS home page: http://www.cazabon.com/pyCMS * pyCMS home page: http://www.cazabon.com/pyCMS
* littleCMS home page: http://www.littlecms.com * littleCMS home page: http://www.littlecms.com
* (littleCMS is Copyright (C) 1998-2001 Marti Maria) * (littleCMS is Copyright (C) 1998-2001 Marti Maria)
* *
* Originally released under LGPL. Graciously donated to PIL in * Originally released under LGPL. Graciously donated to PIL in
* March 2009, for distribution under the standard PIL license * March 2009, for distribution under the standard PIL license
*/ */
@ -55,7 +55,7 @@ http://www.cazabon.com\n\
/* known to-do list with current version: /* known to-do list with current version:
Verify that PILmode->littleCMStype conversion in findLCMStype is correct for all PIL modes (it probably isn't for the more obscure ones) Verify that PILmode->littleCMStype conversion in findLCMStype is correct for all PIL modes (it probably isn't for the more obscure ones)
Add support for creating custom RGB profiles on the fly Add support for creating custom RGB profiles on the fly
Add support for checking presence of a specific tag in a profile Add support for checking presence of a specific tag in a profile
Add support for other littleCMS features as required Add support for other littleCMS features as required
@ -209,7 +209,7 @@ findICmode(icColorSpaceSignature cs)
} }
} }
static DWORD static DWORD
findLCMStype(char* PILmode) findLCMStype(char* PILmode)
{ {
if (strcmp(PILmode, "RGB") == 0) { if (strcmp(PILmode, "RGB") == 0) {
@ -365,7 +365,7 @@ buildProofTransform(PyObject *self, PyObject *args)
cmsErrorAction(LCMS_ERROR_IGNORE); cmsErrorAction(LCMS_ERROR_IGNORE);
transform = _buildProofTransform(pInputProfile->profile, pOutputProfile->profile, pProofProfile->profile, sInMode, sOutMode, iRenderingIntent, iProofIntent, cmsFLAGS); transform = _buildProofTransform(pInputProfile->profile, pOutputProfile->profile, pProofProfile->profile, sInMode, sOutMode, iRenderingIntent, iProofIntent, cmsFLAGS);
if (!transform) if (!transform)
return NULL; return NULL;

View File

@ -132,7 +132,7 @@ getfont(PyObject* self_, PyObject* args, PyObject* kw)
} else { } else {
error = FT_New_Memory_Face(library, (FT_Byte*)font_bytes, font_bytes_size, index, &self->face); error = FT_New_Memory_Face(library, (FT_Byte*)font_bytes, font_bytes_size, index, &self->face);
} }
if (!error) if (!error)
error = FT_Set_Pixel_Sizes(self->face, 0, size); error = FT_Set_Pixel_Sizes(self->face, 0, size);
@ -288,7 +288,7 @@ font_getabc(FontObject* self, PyObject* args)
return geterror(error); return geterror(error);
a = face->glyph->metrics.horiBearingX / 64.0; a = face->glyph->metrics.horiBearingX / 64.0;
b = face->glyph->metrics.width / 64.0; b = face->glyph->metrics.width / 64.0;
c = (face->glyph->metrics.horiAdvance - c = (face->glyph->metrics.horiAdvance -
face->glyph->metrics.horiBearingX - face->glyph->metrics.horiBearingX -
face->glyph->metrics.width) / 64.0; face->glyph->metrics.width) / 64.0;
} else } else

View File

@ -82,7 +82,7 @@ void name(Imaging out, Imaging im1, Imaging im2)\
/* -------------------------------------------------------------------- /* --------------------------------------------------------------------
* some day, we should add FPE protection mechanisms. see pyfpe.h for * some day, we should add FPE protection mechanisms. see pyfpe.h for
* details. * details.
* *
* PyFPE_START_PROTECT("Error in foobar", return 0) * PyFPE_START_PROTECT("Error in foobar", return 0)
* PyFPE_END_PROTECT(result) * PyFPE_END_PROTECT(result)
*/ */
@ -182,7 +182,7 @@ _unop(PyObject* self, PyObject* args)
im1 = (Imaging) i1; im1 = (Imaging) i1;
unop = (void*) op; unop = (void*) op;
unop(out, im1); unop(out, im1);
Py_INCREF(Py_None); Py_INCREF(Py_None);
@ -206,7 +206,7 @@ _binop(PyObject* self, PyObject* args)
im2 = (Imaging) i2; im2 = (Imaging) i2;
binop = (void*) op; binop = (void*) op;
binop(out, im1, im2); binop(out, im1, im2);
Py_INCREF(Py_None); Py_INCREF(Py_None);

View File

@ -30,7 +30,7 @@ typedef struct {
Tcl_Interp* interp; Tcl_Interp* interp;
} TkappObject; } TkappObject;
static PyObject* static PyObject*
_tkinit(PyObject* self, PyObject* args) _tkinit(PyObject* self, PyObject* args)
{ {
Tcl_Interp* interp; Tcl_Interp* interp;

20
_webp.c
View File

@ -60,33 +60,33 @@ PyObject* WebPDecode_wrapper(PyObject* self, PyObject* args)
if (!WebPInitDecoderConfig(&config)) { if (!WebPInitDecoderConfig(&config)) {
Py_RETURN_NONE; Py_RETURN_NONE;
} }
PyBytes_AsStringAndSize((PyObject *) webp_string, (char**)&webp, &size); PyBytes_AsStringAndSize((PyObject *) webp_string, (char**)&webp, &size);
vp8_status_code = WebPGetFeatures(webp, size, &config.input); vp8_status_code = WebPGetFeatures(webp, size, &config.input);
if (vp8_status_code == VP8_STATUS_OK) { if (vp8_status_code == VP8_STATUS_OK) {
// If we don't set it, we don't get alpha. // If we don't set it, we don't get alpha.
// Initialized to MODE_RGB // Initialized to MODE_RGB
if (config.input.has_alpha) { if (config.input.has_alpha) {
config.output.colorspace = MODE_RGBA; config.output.colorspace = MODE_RGBA;
mode = "RGBA"; mode = "RGBA";
} }
vp8_status_code = WebPDecode(webp, size, &config); vp8_status_code = WebPDecode(webp, size, &config);
} }
if (vp8_status_code != VP8_STATUS_OK) { if (vp8_status_code != VP8_STATUS_OK) {
WebPFreeDecBuffer(&config.output); WebPFreeDecBuffer(&config.output);
Py_RETURN_NONE; Py_RETURN_NONE;
} }
if (config.output.colorspace < MODE_YUV) { if (config.output.colorspace < MODE_YUV) {
bytes = PyBytes_FromStringAndSize((char *)config.output.u.RGBA.rgba, bytes = PyBytes_FromStringAndSize((char *)config.output.u.RGBA.rgba,
config.output.u.RGBA.size); config.output.u.RGBA.size);
} else { } else {
// Skipping YUV for now. Need Test Images. // Skipping YUV for now. Need Test Images.
// UNDONE -- unclear if we'll ever get here if we set mode_rgb* // UNDONE -- unclear if we'll ever get here if we set mode_rgb*
bytes = PyBytes_FromStringAndSize((char *)config.output.u.YUVA.y, bytes = PyBytes_FromStringAndSize((char *)config.output.u.YUVA.y,
config.output.u.YUVA.y_size); config.output.u.YUVA.y_size);
} }
@ -95,7 +95,7 @@ PyObject* WebPDecode_wrapper(PyObject* self, PyObject* args)
#else #else
pymode = PyString_FromString(mode); pymode = PyString_FromString(mode);
#endif #endif
ret = Py_BuildValue("SiiS", bytes, config.output.width, ret = Py_BuildValue("SiiS", bytes, config.output.width,
config.output.height, pymode); config.output.height, pymode);
WebPFreeDecBuffer(&config.output); WebPFreeDecBuffer(&config.output);
return ret; return ret;
@ -109,7 +109,7 @@ PyObject* WebPDecoderVersion_wrapper(PyObject* self, PyObject* args){
/* /*
* The version of webp that ships with (0.1.3) Ubuntu 12.04 doesn't handle alpha well. * The version of webp that ships with (0.1.3) Ubuntu 12.04 doesn't handle alpha well.
* Files that are valid with 0.3 are reported as being invalid. * Files that are valid with 0.3 are reported as being invalid.
*/ */
PyObject* WebPDecoderBuggyAlpha_wrapper(PyObject* self, PyObject* args){ PyObject* WebPDecoderBuggyAlpha_wrapper(PyObject* self, PyObject* args){
return Py_BuildValue("i", WebPGetDecoderVersion()==0x0103); return Py_BuildValue("i", WebPGetDecoderVersion()==0x0103);

View File

@ -1,4 +1,4 @@
/* /*
* The Python Imaging Library. * The Python Imaging Library.
* *
* standard decoder interfaces for the Imaging library * standard decoder interfaces for the Imaging library
@ -89,7 +89,7 @@ PyImaging_DecoderNew(int contextsize)
/* Target image */ /* Target image */
decoder->lock = NULL; decoder->lock = NULL;
decoder->im = NULL; decoder->im = NULL;
/* Initialize the cleanup function pointer */ /* Initialize the cleanup function pointer */
decoder->cleanup = NULL; decoder->cleanup = NULL;
@ -105,7 +105,7 @@ _dealloc(ImagingDecoderObject* decoder)
PyObject_Del(decoder); PyObject_Del(decoder);
} }
static PyObject* static PyObject*
_decode(ImagingDecoderObject* decoder, PyObject* args) _decode(ImagingDecoderObject* decoder, PyObject* args)
{ {
UINT8* buffer; UINT8* buffer;
@ -119,7 +119,7 @@ _decode(ImagingDecoderObject* decoder, PyObject* args)
return Py_BuildValue("ii", status, decoder->state.errcode); return Py_BuildValue("ii", status, decoder->state.errcode);
} }
static PyObject* static PyObject*
_decode_cleanup(ImagingDecoderObject* decoder, PyObject* args) _decode_cleanup(ImagingDecoderObject* decoder, PyObject* args)
{ {
int status = 0; int status = 0;
@ -434,15 +434,15 @@ PyImaging_LibTiffDecoderNew(PyObject* self, PyObject* args)
return NULL; return NULL;
TRACE(("new tiff decoder %s\n", compname)); TRACE(("new tiff decoder %s\n", compname));
/* UNDONE -- we can probably do almost any arbitrary compression here, /* UNDONE -- we can probably do almost any arbitrary compression here,
* since we're effective passing in the whole file in one shot and * since we're effective passing in the whole file in one shot and
* getting back the data row by row. V2 maybe * getting back the data row by row. V2 maybe
*/ */
if (strcasecmp(compname, "tiff_ccitt") == 0) { if (strcasecmp(compname, "tiff_ccitt") == 0) {
compression = COMPRESSION_CCITTRLE; compression = COMPRESSION_CCITTRLE;
} else if (strcasecmp(compname, "group3") == 0) { } else if (strcasecmp(compname, "group3") == 0) {
compression = COMPRESSION_CCITTFAX3; compression = COMPRESSION_CCITTFAX3;

View File

@ -71,7 +71,7 @@ _delete(ImagingDisplayObject* display)
PyObject_Del(display); PyObject_Del(display);
} }
static PyObject* static PyObject*
_expose(ImagingDisplayObject* display, PyObject* args) _expose(ImagingDisplayObject* display, PyObject* args)
{ {
int hdc; int hdc;
@ -84,7 +84,7 @@ _expose(ImagingDisplayObject* display, PyObject* args)
return Py_None; return Py_None;
} }
static PyObject* static PyObject*
_draw(ImagingDisplayObject* display, PyObject* args) _draw(ImagingDisplayObject* display, PyObject* args)
{ {
int hdc; int hdc;
@ -128,7 +128,7 @@ _paste(ImagingDisplayObject* display, PyObject* args)
return Py_None; return Py_None;
} }
static PyObject* static PyObject*
_query_palette(ImagingDisplayObject* display, PyObject* args) _query_palette(ImagingDisplayObject* display, PyObject* args)
{ {
int hdc; int hdc;
@ -320,20 +320,20 @@ PyImaging_GrabScreenWin32(PyObject* self, PyObject* args)
BITMAPCOREHEADER core; BITMAPCOREHEADER core;
HDC screen, screen_copy; HDC screen, screen_copy;
PyObject* buffer; PyObject* buffer;
/* step 1: create a memory DC large enough to hold the /* step 1: create a memory DC large enough to hold the
entire screen */ entire screen */
screen = CreateDC("DISPLAY", NULL, NULL, NULL); screen = CreateDC("DISPLAY", NULL, NULL, NULL);
screen_copy = CreateCompatibleDC(screen); screen_copy = CreateCompatibleDC(screen);
width = GetDeviceCaps(screen, HORZRES); width = GetDeviceCaps(screen, HORZRES);
height = GetDeviceCaps(screen, VERTRES); height = GetDeviceCaps(screen, VERTRES);
bitmap = CreateCompatibleBitmap(screen, width, height); bitmap = CreateCompatibleBitmap(screen, width, height);
if (!bitmap) if (!bitmap)
goto error; goto error;
if (!SelectObject(screen_copy, bitmap)) if (!SelectObject(screen_copy, bitmap))
goto error; goto error;
@ -380,7 +380,7 @@ static BOOL CALLBACK list_windows_callback(HWND hwnd, LPARAM lParam)
RECT inner, outer; RECT inner, outer;
int title_size; int title_size;
int status; int status;
/* get window title */ /* get window title */
title_size = GetWindowTextLength(hwnd); title_size = GetWindowTextLength(hwnd);
if (title_size > 0) { if (title_size > 0) {
@ -410,7 +410,7 @@ static BOOL CALLBACK list_windows_callback(HWND hwnd, LPARAM lParam)
if (status < 0) if (status < 0)
return 0; return 0;
return 1; return 1;
} }
@ -418,7 +418,7 @@ PyObject*
PyImaging_ListWindowsWin32(PyObject* self, PyObject* args) PyImaging_ListWindowsWin32(PyObject* self, PyObject* args)
{ {
PyObject* window_list; PyObject* window_list;
window_list = PyList_New(0); window_list = PyList_New(0);
if (!window_list) if (!window_list)
return NULL; return NULL;
@ -444,7 +444,7 @@ PyImaging_GrabClipboardWin32(PyObject* self, PyObject* args)
int size; int size;
void* data; void* data;
PyObject* result; PyObject* result;
int verbose = 0; /* debugging; will be removed in future versions */ int verbose = 0; /* debugging; will be removed in future versions */
if (!PyArg_ParseTuple(args, "|i", &verbose)) if (!PyArg_ParseTuple(args, "|i", &verbose))
return NULL; return NULL;
@ -452,7 +452,7 @@ PyImaging_GrabClipboardWin32(PyObject* self, PyObject* args)
clip = OpenClipboard(NULL); clip = OpenClipboard(NULL);
/* FIXME: check error status */ /* FIXME: check error status */
if (verbose) { if (verbose) {
UINT format = EnumClipboardFormats(0); UINT format = EnumClipboardFormats(0);
char buffer[200]; char buffer[200];
@ -565,7 +565,7 @@ static void
callback_error(const char* handler) callback_error(const char* handler)
{ {
PyObject* sys_stderr; PyObject* sys_stderr;
sys_stderr = PySys_GetObject("stderr"); sys_stderr = PySys_GetObject("stderr");
if (sys_stderr) { if (sys_stderr) {
@ -722,7 +722,7 @@ PyImaging_CreateWindowWin32(PyObject* self, PyObject* args)
wnd = CreateWindowEx( wnd = CreateWindowEx(
0, windowClass.lpszClassName, title, 0, windowClass.lpszClassName, title,
WS_OVERLAPPEDWINDOW, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, width, height, CW_USEDEFAULT, CW_USEDEFAULT, width, height,
HWND_DESKTOP, NULL, NULL, NULL HWND_DESKTOP, NULL, NULL, NULL
); );

View File

@ -480,8 +480,8 @@ Changelog (Pillow)
values, using ordinary [x, y] notation: values, using ordinary [x, y] notation:
pixel = im.load() pixel = im.load()
v = pixel[x, y] v = pixel[x, y]
pixel[x, y] = v pixel[x, y] = v
If you're accessing more than a few pixels, this is a lot If you're accessing more than a few pixels, this is a lot
faster than using getpixel/putpixel. faster than using getpixel/putpixel.
@ -959,7 +959,7 @@ Changelog (Pillow)
+ Change "ImageFont" to reject image files if they don't have the + Change "ImageFont" to reject image files if they don't have the
right mode. Older versions could leak memory for "P" images. right mode. Older versions could leak memory for "P" images.
(Bug reported by Markus Gritsch). (Bug reported by Markus Gritsch).
+ Renamed some internal functions to avoid potential build + Renamed some internal functions to avoid potential build
problem on Mac OS X. problem on Mac OS X.
@ -1039,14 +1039,14 @@ Changelog (Pillow)
This should speed up things like "putdata" and drawing operations. This should speed up things like "putdata" and drawing operations.
+ The Image.offset method is deprecated. Use the ImageChops.offset + The Image.offset method is deprecated. Use the ImageChops.offset
function instead. function instead.
+ Changed ImageChops operators to copy palette and info dictionary + Changed ImageChops operators to copy palette and info dictionary
from the first image argument. from the first image argument.
(1.1.1 released) (1.1.1 released)
+ Additional fixes for Python 1.6/2.0, including TIFF "save" bug. + Additional fixes for Python 1.6/2.0, including TIFF "save" bug.
+ Changed "init" to properly load plugins when PIL is used as a + Changed "init" to properly load plugins when PIL is used as a
package. package.
@ -1242,7 +1242,7 @@ Changelog (Pillow)
+ The ImageDraw "rectangle" method now includes both the right + The ImageDraw "rectangle" method now includes both the right
and the bottom edges when drawing filled rectangles. and the bottom edges when drawing filled rectangles.
+ The TGA decoder now works properly for runlength encoded images + The TGA decoder now works properly for runlength encoded images
which have more than one byte per pixel. which have more than one byte per pixel.
+ "getbands" on an YCbCr image now returns ("Y", "Cb", "Cr") + "getbands" on an YCbCr image now returns ("Y", "Cb", "Cr")
@ -1691,7 +1691,7 @@ Changelog (Pillow)
is a proposed animation standard, based on the PNG file format. is a proposed animation standard, based on the PNG file format.
You can use the "player" sample script to display some flavours You can use the "player" sample script to display some flavours
of this format. The MNG standard is still under development, of this format. The MNG standard is still under development,
as is this driver. More information, including sample files, as is this driver. More information, including sample files,
can be found at <ftp://swrinde.nde.swri.edu/pub/mng> can be found at <ftp://swrinde.nde.swri.edu/pub/mng>

View File

@ -675,7 +675,7 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args)
char* filename; char* filename;
int compression; int compression;
int fp; int fp;
PyObject *dir; PyObject *dir;
PyObject *key, *value; PyObject *key, *value;
Py_ssize_t pos = 0; Py_ssize_t pos = 0;
@ -683,7 +683,7 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args)
Py_ssize_t d_size; Py_ssize_t d_size;
PyObject *keys, *values; PyObject *keys, *values;
if (! PyArg_ParseTuple(args, "sssisO", &mode, &rawmode, &compname, &fp, &filename, &dir)) { if (! PyArg_ParseTuple(args, "sssisO", &mode, &rawmode, &compname, &fp, &filename, &dir)) {
return NULL; return NULL;
@ -705,14 +705,14 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args)
TRACE(("new tiff encoder %s fp: %d, filename: %s \n", compname, fp, filename)); TRACE(("new tiff encoder %s fp: %d, filename: %s \n", compname, fp, filename));
/* UNDONE -- we can probably do almost any arbitrary compression here, /* UNDONE -- we can probably do almost any arbitrary compression here,
* so long as we're doing row/stripe based actions and not tiles. * so long as we're doing row/stripe based actions and not tiles.
*/ */
if (strcasecmp(compname, "tiff_ccitt") == 0) { if (strcasecmp(compname, "tiff_ccitt") == 0) {
compression = COMPRESSION_CCITTRLE; compression = COMPRESSION_CCITTRLE;
} else if (strcasecmp(compname, "group3") == 0) { } else if (strcasecmp(compname, "group3") == 0) {
compression = COMPRESSION_CCITTFAX3; compression = COMPRESSION_CCITTFAX3;
@ -751,12 +751,12 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args)
TRACE(("Attempting to set key: %d\n", (int)PyInt_AsLong(key))); TRACE(("Attempting to set key: %d\n", (int)PyInt_AsLong(key)));
if (PyInt_Check(value)) { if (PyInt_Check(value)) {
TRACE(("Setting from Int: %d %ld \n", (int)PyInt_AsLong(key),PyInt_AsLong(value))); TRACE(("Setting from Int: %d %ld \n", (int)PyInt_AsLong(key),PyInt_AsLong(value)));
status = ImagingLibTiffSetField(&encoder->state, status = ImagingLibTiffSetField(&encoder->state,
(ttag_t) PyInt_AsLong(key), (ttag_t) PyInt_AsLong(key),
PyInt_AsLong(value)); PyInt_AsLong(value));
} else if(PyBytes_Check(value)) { } else if(PyBytes_Check(value)) {
TRACE(("Setting from String: %d, %s \n", (int)PyInt_AsLong(key),PyBytes_AsString(value))); TRACE(("Setting from String: %d, %s \n", (int)PyInt_AsLong(key),PyBytes_AsString(value)));
status = ImagingLibTiffSetField(&encoder->state, status = ImagingLibTiffSetField(&encoder->state,
(ttag_t) PyInt_AsLong(key), (ttag_t) PyInt_AsLong(key),
PyBytes_AsString(value)); PyBytes_AsString(value));
@ -771,18 +771,18 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args)
for (i=0;i<len;i++) { for (i=0;i<len;i++) {
floatav[i] = (float)PyFloat_AsDouble(PyList_GetItem(value,i)); floatav[i] = (float)PyFloat_AsDouble(PyList_GetItem(value,i));
} }
status = ImagingLibTiffSetField(&encoder->state, status = ImagingLibTiffSetField(&encoder->state,
(ttag_t) PyInt_AsLong(key), (ttag_t) PyInt_AsLong(key),
floatav); floatav);
free(floatav); free(floatav);
} }
} else if (PyFloat_Check(value)) { } else if (PyFloat_Check(value)) {
TRACE(("Setting from String: %d, %f \n", (int)PyInt_AsLong(key),PyFloat_AsDouble(value))); TRACE(("Setting from String: %d, %f \n", (int)PyInt_AsLong(key),PyFloat_AsDouble(value)));
status = ImagingLibTiffSetField(&encoder->state, status = ImagingLibTiffSetField(&encoder->state,
(ttag_t) PyInt_AsLong(key), (ttag_t) PyInt_AsLong(key),
(float)PyFloat_AsDouble(value)); (float)PyFloat_AsDouble(value));
} else { } else {
TRACE(("Unhandled type for key %d : %s ", TRACE(("Unhandled type for key %d : %s ",
(int)PyInt_AsLong(key), (int)PyInt_AsLong(key),
PyBytes_AsString(PyObject_Str(value)))); PyBytes_AsString(PyObject_Str(value))));
} }
@ -793,7 +793,7 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args)
return NULL; return NULL;
} }
} }
encoder->encode = ImagingLibTiffEncode; encoder->encode = ImagingLibTiffEncode;
return (PyObject*) encoder; return (PyObject*) encoder;

View File

@ -17,7 +17,7 @@
#define ACCESS_TABLE_HASH 30197 #define ACCESS_TABLE_HASH 30197
static struct ImagingAccessInstance access_table[ACCESS_TABLE_SIZE]; static struct ImagingAccessInstance access_table[ACCESS_TABLE_SIZE];
static inline UINT32 static inline UINT32
hash(const char* mode) hash(const char* mode)
{ {

View File

@ -2,7 +2,7 @@
* The Python Imaging Library * The Python Imaging Library
* $Id$ * $Id$
* *
* pilopen antialiasing support * pilopen antialiasing support
* *
* history: * history:
* 2002-03-09 fl Created (for PIL 1.1.3) * 2002-03-09 fl Created (for PIL 1.1.3)
@ -133,7 +133,7 @@ ImagingStretch(Imaging imOut, Imaging imIn, int filter)
filterscale = 1.0; filterscale = 1.0;
support = 0.5; support = 0.5;
} }
support = support * filterscale; support = support * filterscale;
/* coefficient buffer (with rounding safety margin) */ /* coefficient buffer (with rounding safety margin) */

View File

@ -1,7 +1,7 @@
/* /*
* The Python Imaging Library * The Python Imaging Library
* $Id$ * $Id$
* *
* stuff to extract and paste back individual bands * stuff to extract and paste back individual bands
* *
* history: * history:

View File

@ -75,7 +75,7 @@ ImagingBitDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
bitstate->bitbuffer = (bitstate->bitbuffer << 8) | byte; bitstate->bitbuffer = (bitstate->bitbuffer << 8) | byte;
bitstate->bitcount += 8; bitstate->bitcount += 8;
while (bitstate->bitcount >= bitstate->bits) { while (bitstate->bitcount >= bitstate->bits) {
/* get a pixel from the bit buffer */ /* get a pixel from the bit buffer */
@ -127,7 +127,7 @@ ImagingBitDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
return -1; return -1;
} }
state->x = 0; state->x = 0;
/* reset bit buffer */ /* reset bit buffer */
if (bitstate->pad > 0) if (bitstate->pad > 0)
bitstate->bitcount = 0; bitstate->bitcount = 0;
} }

View File

@ -1,4 +1,4 @@
/* /*
* The Python Imaging Library * The Python Imaging Library
* $Id$ * $Id$
* *

View File

@ -1,4 +1,4 @@
/* /*
* The Python Imaging Library * The Python Imaging Library
* $Id$ * $Id$
* *

View File

@ -1,7 +1,7 @@
/* /*
* The Python Imaging Library * The Python Imaging Library
* $Id$ * $Id$
* *
* convert images * convert images
* *
* history: * history:
@ -1055,7 +1055,7 @@ convert(Imaging imOut, Imaging imIn, const char *mode,
if (strcmp(imIn->mode, "P") == 0 || strcmp(imIn->mode, "PA") == 0) if (strcmp(imIn->mode, "P") == 0 || strcmp(imIn->mode, "PA") == 0)
return frompalette(imOut, imIn, mode); return frompalette(imOut, imIn, mode);
if (strcmp(mode, "P") == 0) if (strcmp(mode, "P") == 0)
return topalette(imOut, imIn, palette, dither); return topalette(imOut, imIn, palette, dither);
@ -1126,7 +1126,7 @@ ImagingConvertInPlace(Imaging imIn, const char* mode)
convert = bit2l; convert = bit2l;
else else
return ImagingError_ModeError(); return ImagingError_ModeError();
ImagingSectionEnter(&cookie); ImagingSectionEnter(&cookie);
for (y = 0; y < imIn->ysize; y++) for (y = 0; y < imIn->ysize; y++)
(*convert)((UINT8*) imIn->image[y], (UINT8*) imIn->image[y], (*convert)((UINT8*) imIn->image[y], (UINT8*) imIn->image[y],

View File

@ -352,7 +352,7 @@ ImagingConvertRGB2YCbCr(UINT8* out, const UINT8* in, int pixels)
y = (Y_R[r] + Y_G[g] + Y_B[b]) >> SCALE; y = (Y_R[r] + Y_G[g] + Y_B[b]) >> SCALE;
cb = ((Cb_R[r] + Cb_G[g] + Cb_B[b]) >> SCALE) + 128; cb = ((Cb_R[r] + Cb_G[g] + Cb_B[b]) >> SCALE) + 128;
cr = ((Cr_R[r] + Cr_G[g] + Cr_B[b]) >> SCALE) + 128; cr = ((Cr_R[r] + Cr_G[g] + Cr_B[b]) >> SCALE) + 128;
out[0] = (UINT8) y; out[0] = (UINT8) y;
out[1] = (UINT8) cb; out[1] = (UINT8) cb;
out[2] = (UINT8) cr; out[2] = (UINT8) cr;

View File

@ -1,4 +1,4 @@
/* /*
* The Python Imaging Library * The Python Imaging Library
* $Id$ * $Id$
* *

View File

@ -26,7 +26,7 @@ ImagingCrop(Imaging imIn, int sx0, int sy0, int sx1, int sy1)
int xsize, ysize; int xsize, ysize;
int dx0, dy0, dx1, dy1; int dx0, dy0, dx1, dy1;
INT32 zero = 0; INT32 zero = 0;
if (!imIn) if (!imIn)
return (Imaging) ImagingError_ModeError(); return (Imaging) ImagingError_ModeError();

View File

@ -126,7 +126,7 @@ ImagingNewDIB(const char *mode, int xsize, int ysize)
/* Bind a palette to it as well (only required for 8-bit DIBs) */ /* Bind a palette to it as well (only required for 8-bit DIBs) */
if (dib->pixelsize == 1) { if (dib->pixelsize == 1) {
for (i = 0; i < 256; i++) { for (i = 0; i < 256; i++) {
palette[i].rgbRed = palette[i].rgbRed =
palette[i].rgbGreen = palette[i].rgbGreen =
palette[i].rgbBlue = i; palette[i].rgbBlue = i;
palette[i].rgbReserved = 0; palette[i].rgbReserved = 0;
@ -181,7 +181,7 @@ ImagingNewDIB(const char *mode, int xsize, int ysize)
i++; i++;
} }
for (r = 1; r < 22-1; r++) { for (r = 1; r < 22-1; r++) {
/* Black and white are already provided by the cube. */ /* Black and white are already provided by the cube. */
pal->palPalEntry[i].peRed = pal->palPalEntry[i].peRed =
pal->palPalEntry[i].peGreen = pal->palPalEntry[i].peGreen =
pal->palPalEntry[i].peBlue = r * 255 / (22-1); pal->palPalEntry[i].peBlue = r * 255 / (22-1);

View File

@ -436,7 +436,7 @@ polygon8(Imaging im, int n, Edge *e, int ink, int eofill)
for (;ymin <= ymax; ymin++) { for (;ymin <= ymax; ymin++) {
y = ymin+0.5F; y = ymin+0.5F;
for (i = j = 0; i < n; i++) for (i = j = 0; i < n; i++)
if (y >= e[i].ymin && y <= e[i].ymax) { if (y >= e[i].ymin && y <= e[i].ymax) {
if (e[i].d == 0) if (e[i].d == 0)
hline8(im, e[i].xmin, ymin, e[i].xmax, ink); hline8(im, e[i].xmin, ymin, e[i].xmax, ink);
@ -590,7 +590,7 @@ add_edge(Edge *e, int x0, int y0, int x1, int y1)
e->ymin = y0, e->ymax = y1; e->ymin = y0, e->ymax = y1;
else else
e->ymin = y1, e->ymax = y0; e->ymin = y1, e->ymax = y0;
if (y0 == y1) { if (y0 == y1) {
e->d = 0; e->d = 0;
e->dx = 0.0; e->dx = 0.0;
@ -777,7 +777,7 @@ ImagingDrawPolygon(Imaging im, int count, int* xy, const void* ink_,
draw->line(im, xy[i+i], xy[i+i+1], xy[0], xy[1], ink); draw->line(im, xy[i+i], xy[i+i+1], xy[0], xy[1], ink);
} }
return 0; return 0;
} }
@ -861,7 +861,7 @@ ellipse(Imaging im, int x0, int y0, int x1, int y1,
} }
free(e); free(e);
} else { } else {
for (i = start; i <= end; i++) { for (i = start; i <= end; i++) {
@ -1017,7 +1017,7 @@ ImagingOutlineLine(ImagingOutline outline, float x1, float y1)
outline->x = x1; outline->x = x1;
outline->y = y1; outline->y = y1;
return 0; return 0;
} }
@ -1061,13 +1061,13 @@ ImagingOutlineCurve(ImagingOutline outline, float x1, float y1,
outline->x = xo; outline->x = xo;
outline->y = yo; outline->y = yo;
return 0; return 0;
} }
int int
ImagingOutlineCurve2(ImagingOutline outline, float cx, float cy, ImagingOutlineCurve2(ImagingOutline outline, float cx, float cy,
float x3, float y3) float x3, float y3)
{ {
/* add bezier curve based on three control points (as /* add bezier curve based on three control points (as
in the Flash file format) */ in the Flash file format) */
@ -1095,13 +1095,13 @@ ImagingOutlineTransform(ImagingOutline outline, double a[6])
int i, n; int i, n;
int x0, y0, x1, y1; int x0, y0, x1, y1;
int X0, Y0, X1, Y1; int X0, Y0, X1, Y1;
double a0 = a[0]; double a1 = a[1]; double a2 = a[2]; double a0 = a[0]; double a1 = a[1]; double a2 = a[2];
double a3 = a[3]; double a4 = a[4]; double a5 = a[5]; double a3 = a[3]; double a4 = a[4]; double a5 = a[5];
eIn = outline->edges; eIn = outline->edges;
n = outline->count; n = outline->count;
/* FIXME: ugly! */ /* FIXME: ugly! */
outline->edges = NULL; outline->edges = NULL;
outline->count = outline->size = 0; outline->count = outline->size = 0;
@ -1113,12 +1113,12 @@ ImagingOutlineTransform(ImagingOutline outline, double a[6])
ImagingError_MemoryError(); ImagingError_MemoryError();
return -1; return -1;
} }
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
x0 = eIn->x0; x0 = eIn->x0;
y0 = eIn->y0; y0 = eIn->y0;
/* FIXME: ouch! */ /* FIXME: ouch! */
if (eIn->x0 == eIn->xmin) if (eIn->x0 == eIn->xmin)
x1 = eIn->xmax; x1 = eIn->xmax;

View File

@ -1,4 +1,4 @@
/* /*
* The Python Imaging Library * The Python Imaging Library
* $Id$ * $Id$
* *

View File

@ -1,4 +1,4 @@
/* /*
* The Python Imaging Library. * The Python Imaging Library.
* $Id$ * $Id$
* *
@ -76,5 +76,5 @@ ImagingEpsEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
} }
return ptr - buf; return ptr - buf;
} }

View File

@ -1,4 +1,4 @@
/* /*
* The Python Imaging Library * The Python Imaging Library
* $Id$ * $Id$
* *

View File

@ -57,7 +57,7 @@ ImagingOpenPPM(const char* infile)
x = y = max = 0; x = y = max = 0;
while (i < 3) { while (i < 3) {
/* Ignore optional comment fields */ /* Ignore optional comment fields */
while (c == '\n') { while (c == '\n') {

View File

@ -31,7 +31,7 @@ ImagingExpand(Imaging imIn, int xmargin, int ymargin, int mode)
{ {
Imaging imOut; Imaging imOut;
int x, y; int x, y;
if (xmargin < 0 && ymargin < 0) if (xmargin < 0 && ymargin < 0)
return (Imaging) ImagingError_ValueError("bad kernel size"); return (Imaging) ImagingError_ValueError("bad kernel size");

View File

@ -583,7 +583,7 @@ getfilter(Imaging im, int filterid)
Imaging Imaging
ImagingTransform( ImagingTransform(
Imaging imOut, Imaging imIn, int x0, int y0, int x1, int y1, Imaging imOut, Imaging imIn, int x0, int y0, int x1, int y1,
ImagingTransformMap transform, void* transform_data, ImagingTransformMap transform, void* transform_data,
ImagingTransformFilter filter, void* filter_data, ImagingTransformFilter filter, void* filter_data,
int fill) int fill)

View File

@ -1,4 +1,4 @@
/* /*
* The Python Imaging Library * The Python Imaging Library
* $Id$ * $Id$
* *
@ -224,7 +224,7 @@ getcolors32(Imaging im, int maxcolors, int* size)
33554432,9, 67108864,71, 134217728,39, 268435456,9, 536870912,5, 33554432,9, 67108864,71, 134217728,39, 268435456,9, 536870912,5,
1073741824,83, 0 1073741824,83, 0
}; };
code_size = code_poly = code_mask = 0; code_size = code_poly = code_mask = 0;
for (i = 0; SIZES[i]; i += 2) { for (i = 0; SIZES[i]; i += 2) {

View File

@ -75,7 +75,7 @@ ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8* buffer, int bytes)
state->errcode = IMAGING_CODEC_CONFIG; state->errcode = IMAGING_CODEC_CONFIG;
return -1; return -1;
} }
/* Clear code */ /* Clear code */
context->clear = 1 << context->bits; context->clear = 1 << context->bits;

View File

@ -44,7 +44,7 @@ emit(GIFENCODERSTATE *context, int byte)
/* no room in the current block (or no current block); /* no room in the current block (or no current block);
allocate a new one */ allocate a new one */
/* add current block to end of flush queue */ /* add current block to end of flush queue */
if (context->block) { if (context->block) {
block = context->flush; block = context->flush;

View File

@ -1,4 +1,4 @@
/* /*
* The Python Imaging Library * The Python Imaging Library
* $Id$ * $Id$
* *

View File

@ -1,7 +1,7 @@
/* /*
* The Python Imaging Library * The Python Imaging Library
* $Id$ * $Id$
* *
* declarations for the imaging core library * declarations for the imaging core library
* *
* Copyright (c) 1997-2005 by Secret Labs AB * Copyright (c) 1997-2005 by Secret Labs AB
@ -291,16 +291,16 @@ extern Imaging ImagingRotate180(Imaging imOut, Imaging imIn);
extern Imaging ImagingRotate270(Imaging imOut, Imaging imIn); extern Imaging ImagingRotate270(Imaging imOut, Imaging imIn);
extern Imaging ImagingStretch(Imaging imOut, Imaging imIn, int filter); extern Imaging ImagingStretch(Imaging imOut, Imaging imIn, int filter);
extern Imaging ImagingTransformPerspective( extern Imaging ImagingTransformPerspective(
Imaging imOut, Imaging imIn, int x0, int y0, int x1, int y1, Imaging imOut, Imaging imIn, int x0, int y0, int x1, int y1,
double a[8], int filter, int fill); double a[8], int filter, int fill);
extern Imaging ImagingTransformAffine( extern Imaging ImagingTransformAffine(
Imaging imOut, Imaging imIn, int x0, int y0, int x1, int y1, Imaging imOut, Imaging imIn, int x0, int y0, int x1, int y1,
double a[6], int filter, int fill); double a[6], int filter, int fill);
extern Imaging ImagingTransformQuad( extern Imaging ImagingTransformQuad(
Imaging imOut, Imaging imIn, int x0, int y0, int x1, int y1, Imaging imOut, Imaging imIn, int x0, int y0, int x1, int y1,
double a[8], int filter, int fill); double a[8], int filter, int fill);
extern Imaging ImagingTransform( extern Imaging ImagingTransform(
Imaging imOut, Imaging imIn, int x0, int y0, int x1, int y1, Imaging imOut, Imaging imIn, int x0, int y0, int x1, int y1,
ImagingTransformMap transform, void* transform_data, ImagingTransformMap transform, void* transform_data,
ImagingTransformFilter filter, void* filter_data, ImagingTransformFilter filter, void* filter_data,
int fill); int fill);
@ -373,7 +373,7 @@ extern int ImagingOutlineLine(ImagingOutline outline, float x, float y);
extern int ImagingOutlineCurve(ImagingOutline outline, float x1, float y1, extern int ImagingOutlineCurve(ImagingOutline outline, float x1, float y1,
float x2, float y2, float x3, float y3); float x2, float y2, float x3, float y3);
extern int ImagingOutlineTransform(ImagingOutline outline, double a[6]); extern int ImagingOutlineTransform(ImagingOutline outline, double a[6]);
extern int ImagingOutlineClose(ImagingOutline outline); extern int ImagingOutlineClose(ImagingOutline outline);
/* Special effects */ /* Special effects */

View File

@ -103,7 +103,7 @@ typedef struct {
JPEGDESTINATION destination; JPEGDESTINATION destination;
int extra_offset; int extra_offset;
int rawExifLen; /* EXIF data length */ int rawExifLen; /* EXIF data length */
char* rawExif; /* EXIF buffer pointer */ char* rawExif; /* EXIF buffer pointer */

View File

@ -15,8 +15,8 @@
* 2000-10-12 fl Suppress warnings * 2000-10-12 fl Suppress warnings
* 2000-12-04 fl Suppress errors beyond end of image data * 2000-12-04 fl Suppress errors beyond end of image data
* *
* Copyright (c) 1998-2000 Secret Labs AB * Copyright (c) 1998-2000 Secret Labs AB
* Copyright (c) 1996-2000 Fredrik Lundh * Copyright (c) 1996-2000 Fredrik Lundh
* *
* See the README file for details on usage and redistribution. * See the README file for details on usage and redistribution.
*/ */
@ -26,9 +26,9 @@
#ifdef HAVE_LIBJPEG #ifdef HAVE_LIBJPEG
#undef HAVE_PROTOTYPES #undef HAVE_PROTOTYPES
#undef HAVE_STDLIB_H #undef HAVE_STDLIB_H
#undef HAVE_STDDEF_H #undef HAVE_STDDEF_H
#undef UINT8 #undef UINT8
#undef UINT16 #undef UINT16
#undef UINT32 #undef UINT32
@ -148,7 +148,7 @@ ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
if (context->source.skip > 0) { if (context->source.skip > 0) {
skip_input_data(&context->cinfo, context->source.skip); skip_input_data(&context->cinfo, context->source.skip);
if (context->source.skip > 0) if (context->source.skip > 0)
return context->source.pub.next_input_byte - buf; return context->source.pub.next_input_byte - buf;
} }
switch (state->state) { switch (state->state) {
@ -157,7 +157,7 @@ ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
/* Read JPEG header, until we find an image body. */ /* Read JPEG header, until we find an image body. */
do { do {
/* Note that we cannot return unless we have decoded /* Note that we cannot return unless we have decoded
as much data as possible. */ as much data as possible. */
ok = jpeg_read_header(&context->cinfo, FALSE); ok = jpeg_read_header(&context->cinfo, FALSE);
@ -220,7 +220,7 @@ ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
file if necessary to return data line by line) */ file if necessary to return data line by line) */
if (!jpeg_start_decompress(&context->cinfo)) if (!jpeg_start_decompress(&context->cinfo))
break; break;
state->state++; state->state++;
/* fall through */ /* fall through */
@ -259,7 +259,7 @@ ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
} }
/* Return number of bytes consumed */ /* Return number of bytes consumed */
return context->source.pub.next_input_byte - buf; return context->source.pub.next_input_byte - buf;
} }
@ -268,8 +268,8 @@ ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
/* -------------------------------------------------------------------- */ /* -------------------------------------------------------------------- */
int ImagingJpegDecodeCleanup(ImagingCodecState state){ int ImagingJpegDecodeCleanup(ImagingCodecState state){
/* called to fee the decompression engine when the decode terminates /* called to fee the decompression engine when the decode terminates
due to a corrupt or truncated image due to a corrupt or truncated image
*/ */
JPEGSTATE* context = (JPEGSTATE*) state->context; JPEGSTATE* context = (JPEGSTATE*) state->context;

View File

@ -229,13 +229,13 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
/* fall through */ /* fall through */
case 2: case 2:
// check for exif len + 'APP1' header bytes // check for exif len + 'APP1' header bytes
if (context->rawExifLen + 5 > context->destination.pub.free_in_buffer){ if (context->rawExifLen + 5 > context->destination.pub.free_in_buffer){
break; break;
} }
//add exif header //add exif header
if (context->rawExifLen > 0){ if (context->rawExifLen > 0){
jpeg_write_marker(&context->cinfo, JPEG_APP0+1, jpeg_write_marker(&context->cinfo, JPEG_APP0+1,
(unsigned char*)context->rawExif, context->rawExifLen); (unsigned char*)context->rawExif, context->rawExifLen);
} }

View File

@ -69,7 +69,7 @@ ImagingModeFilter(Imaging im, int size)
out[x] = IMAGING_PIXEL_L(im, x, y); out[x] = IMAGING_PIXEL_L(im, x, y);
} }
} }
ImagingCopyInfo(imOut, im); ImagingCopyInfo(imOut, im);

View File

@ -7,7 +7,7 @@
* history: * history:
* 96-03-27 fl Created * 96-03-27 fl Created
* 96-07-16 fl Support "1", "L" and "RGBA" masks * 96-07-16 fl Support "1", "L" and "RGBA" masks
* 96-08-16 fl Merged with opaque paste * 96-08-16 fl Merged with opaque paste
* 97-01-17 fl Faster blending, added support for RGBa images * 97-01-17 fl Faster blending, added support for RGBa images
* 97-08-27 fl Faster masking for 32-bit images * 97-08-27 fl Faster masking for 32-bit images
* 98-02-02 fl Fixed MULDIV255 macro for gcc * 98-02-02 fl Fixed MULDIV255 macro for gcc
@ -209,7 +209,7 @@ paste_mask_RGBa(Imaging imOut, Imaging imIn, Imaging imMask,
} }
} }
} }
int int
ImagingPaste(Imaging imOut, Imaging imIn, Imaging imMask, ImagingPaste(Imaging imOut, Imaging imIn, Imaging imMask,
int dx0, int dy0, int dx1, int dy1) int dx0, int dy0, int dx1, int dy1)
@ -310,7 +310,7 @@ fill(Imaging imOut, const void* ink_, int dx, int dy,
xsize *= pixelsize; xsize *= pixelsize;
for (y = 0; y < ysize; y++) for (y = 0; y < ysize; y++)
memset(imOut->image[y+dy]+dx, ink8, xsize); memset(imOut->image[y+dy]+dx, ink8, xsize);
} else { } else {
for (y = 0; y < ysize; y++) { for (y = 0; y < ysize; y++) {

View File

@ -37,7 +37,7 @@ ImagingPcdDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
for (;;) { for (;;) {
/* We need data for two full lines before we can do anything */ /* We need data for two full lines before we can do anything */
if (bytes < chunk) if (bytes < chunk)
return ptr - buf; return ptr - buf;

View File

@ -36,7 +36,7 @@ ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
return ptr - buf; return ptr - buf;
n = ptr[0] & 0x3F; n = ptr[0] & 0x3F;
while (n > 0) { while (n > 0) {
if (state->x >= state->bytes) { if (state->x >= state->bytes) {
state->errcode = IMAGING_CODEC_OVERRUN; state->errcode = IMAGING_CODEC_OVERRUN;

View File

@ -207,8 +207,8 @@ ImagingPointTransform(Imaging imIn, double scale, double offset)
Imaging imOut; Imaging imOut;
int x, y; int x, y;
if (!imIn || (strcmp(imIn->mode, "I") != 0 && if (!imIn || (strcmp(imIn->mode, "I") != 0 &&
strcmp(imIn->mode, "I;16") != 0 && strcmp(imIn->mode, "I;16") != 0 &&
strcmp(imIn->mode, "F") != 0)) strcmp(imIn->mode, "F") != 0))
return (Imaging) ImagingError_ModeError(); return (Imaging) ImagingError_ModeError();

View File

@ -11,7 +11,7 @@
* 2005-02-07 fl Limit number of colors to 256 * 2005-02-07 fl Limit number of colors to 256
* *
* Written by Toby J Sargeant <tjs@longford.cs.monash.edu.au>. * Written by Toby J Sargeant <tjs@longford.cs.monash.edu.au>.
* *
* Copyright (c) 1998 by Toby J Sargeant * Copyright (c) 1998 by Toby J Sargeant
* Copyright (c) 1998-2004 by Secret Labs AB. All rights reserved. * Copyright (c) 1998-2004 by Secret Labs AB. All rights reserved.
* *
@ -235,7 +235,7 @@ hash_to_list(const HashTable *h, const Pixel pixel, const uint32_t count, void *
p=malloc(sizeof(PixelList)); p=malloc(sizeof(PixelList));
if (!p) return; if (!p) return;
p->flag=0; p->flag=0;
p->p=q; p->p=q;
p->count=count; p->count=count;
@ -484,7 +484,7 @@ split(BoxNode *node)
#ifdef TEST_SPLIT #ifdef TEST_SPLIT
printf ("along axis %d\n",axis+1); printf ("along axis %d\n",axis+1);
#endif #endif
#ifdef TEST_SPLIT #ifdef TEST_SPLIT
{ {
PixelList *_prevTest,*_nextTest; PixelList *_prevTest,*_nextTest;
@ -951,7 +951,7 @@ compute_palette_from_median_cut(
Pixel *p; Pixel *p;
uint32_t *avg[3]; uint32_t *avg[3];
uint32_t *count; uint32_t *count;
*palette=NULL; *palette=NULL;
if (!(count=malloc(sizeof(uint32_t)*nPaletteEntries))) { if (!(count=malloc(sizeof(uint32_t)*nPaletteEntries))) {
return 0; return 0;
@ -1088,7 +1088,7 @@ k_means(Pixel *pixelData,
uint32_t **avgDistSortKey; uint32_t **avgDistSortKey;
int changes; int changes;
int built=0; int built=0;
if (!(count=malloc(sizeof(uint32_t)*nPaletteEntries))) { if (!(count=malloc(sizeof(uint32_t)*nPaletteEntries))) {
return 0; return 0;
} }
@ -1169,11 +1169,11 @@ quantize(Pixel *pixelData,
uint32_t i; uint32_t i;
uint32_t *qp; uint32_t *qp;
uint32_t nPaletteEntries; uint32_t nPaletteEntries;
uint32_t *avgDist; uint32_t *avgDist;
uint32_t **avgDistSortKey; uint32_t **avgDistSortKey;
Pixel *p; Pixel *p;
#ifndef NO_OUTPUT #ifndef NO_OUTPUT
uint32_t timer,timer2; uint32_t timer,timer2;
#endif #endif
@ -1560,7 +1560,7 @@ ImagingQuantize(Imaging im, int colors, int mode, int kmeans)
break; break;
case 2: case 2:
if (!strcmp(im->mode, "RGBA")) { if (!strcmp(im->mode, "RGBA")) {
withAlpha = 1; withAlpha = 1;
} }
result = quantize_octree( result = quantize_octree(
p, p,

View File

@ -194,7 +194,7 @@ static int _hashtable_insert(HashTable *h,HashKey_t key,HashVal_t val,int resize
HashNode *t; HashNode *t;
int i; int i;
uint32_t hash=h->hashFunc(h,key)%h->length; uint32_t hash=h->hashFunc(h,key)%h->length;
for (n=&(h->table[hash]);*n;n=&((*n)->next)) { for (n=&(h->table[hash]);*n;n=&((*n)->next)) {
nv=*n; nv=*n;
i=h->cmpFunc(h,nv->key,key); i=h->cmpFunc(h,nv->key,key);
@ -226,7 +226,7 @@ static int _hashtable_lookup_or_insert(HashTable *h,HashKey_t key,HashVal_t *ret
HashNode *t; HashNode *t;
int i; int i;
uint32_t hash=h->hashFunc(h,key)%h->length; uint32_t hash=h->hashFunc(h,key)%h->length;
for (n=&(h->table[hash]);*n;n=&((*n)->next)) { for (n=&(h->table[hash]);*n;n=&((*n)->next)) {
nv=*n; nv=*n;
i=h->cmpFunc(h,nv->key,key); i=h->cmpFunc(h,nv->key,key);
@ -257,7 +257,7 @@ int hashtable_insert_or_update_computed(HashTable *h,
HashNode *t; HashNode *t;
int i; int i;
uint32_t hash=h->hashFunc(h,key)%h->length; uint32_t hash=h->hashFunc(h,key)%h->length;
for (n=&(h->table[hash]);*n;n=&((*n)->next)) { for (n=&(h->table[hash]);*n;n=&((*n)->next)) {
nv=*n; nv=*n;
i=h->cmpFunc(h,nv->key,key); i=h->cmpFunc(h,nv->key,key);
@ -367,7 +367,7 @@ static int _hashtable_remove(HashTable *h,
uint32_t hash=h->hashFunc(h,key)%h->length; uint32_t hash=h->hashFunc(h,key)%h->length;
HashNode *n,*p; HashNode *n,*p;
int i; int i;
for (p=NULL,n=h->table[hash];n;p=n,n=n->next) { for (p=NULL,n=h->table[hash];n;p=n,n=n->next) {
i=h->cmpFunc(h,n->key,key); i=h->cmpFunc(h,n->key,key);
if (!i) { if (!i) {
@ -388,7 +388,7 @@ static int _hashtable_delete(HashTable *h,const HashKey_t key,int resize) {
uint32_t hash=h->hashFunc(h,key)%h->length; uint32_t hash=h->hashFunc(h,key)%h->length;
HashNode *n,*p; HashNode *n,*p;
int i; int i;
for (p=NULL,n=h->table[hash];n;p=n,n=n->next) { for (p=NULL,n=h->table[hash];n;p=n,n=n->next) {
i=h->cmpFunc(h,n->key,key); i=h->cmpFunc(h,n->key,key);
if (!i) { if (!i) {
@ -429,7 +429,7 @@ int hashtable_lookup(const HashTable *h,const HashKey_t key,HashVal_t *valp) {
uint32_t hash=h->hashFunc(h,key)%h->length; uint32_t hash=h->hashFunc(h,key)%h->length;
HashNode *n; HashNode *n;
int i; int i;
for (n=h->table[hash];n;n=n->next) { for (n=h->table[hash];n;n=n->next) {
i=h->cmpFunc(h,n->key,key); i=h->cmpFunc(h,n->key,key);
if (!i) { if (!i) {

View File

@ -131,7 +131,7 @@ int ImagingQuantHeapTop(Heap *h,void **r) {
Heap *ImagingQuantHeapNew(HeapCmpFunc cf) { Heap *ImagingQuantHeapNew(HeapCmpFunc cf) {
Heap *h; Heap *h;
h=malloc(sizeof(Heap)); h=malloc(sizeof(Heap));
if (!h) return NULL; if (!h) return NULL;
h->heapsize=INITIAL_SIZE; h->heapsize=INITIAL_SIZE;

View File

@ -95,7 +95,7 @@ ImagingRankFilter(Imaging im, int size, int rank)
ImagingDelete(imOut); ImagingDelete(imOut);
return (Imaging) ImagingError_ModeError(); return (Imaging) ImagingError_ModeError();
} }
ImagingCopyInfo(imOut, im); ImagingCopyInfo(imOut, im);
return imOut; return imOut;

View File

@ -69,7 +69,7 @@ ImagingRawDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
return ptr - buf; return ptr - buf;
/* Unpack data */ /* Unpack data */
state->shuffle((UINT8*) im->image[state->y + state->yoff] + state->shuffle((UINT8*) im->image[state->y + state->yoff] +
state->xoff * im->pixelsize, ptr, state->xsize); state->xoff * im->pixelsize, ptr, state->xsize);
ptr += state->bytes; ptr += state->bytes;

View File

@ -28,7 +28,7 @@
* 2003-09-26 fl Added "LA" and "PA" modes (experimental) * 2003-09-26 fl Added "LA" and "PA" modes (experimental)
* 2005-10-02 fl Added image counter * 2005-10-02 fl Added image counter
* *
* Copyright (c) 1998-2005 by Secret Labs AB * Copyright (c) 1998-2005 by Secret Labs AB
* Copyright (c) 1995-2005 by Fredrik Lundh * Copyright (c) 1995-2005 by Fredrik Lundh
* *
* See the README file for information on usage and redistribution. * See the README file for information on usage and redistribution.

View File

@ -62,7 +62,7 @@ ImagingSunRleDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
} }
memset(state->buffer + state->x, ptr[2], n); memset(state->buffer + state->x, ptr[2], n);
ptr += 3; ptr += 3;
bytes -= 3; bytes -= 3;

View File

@ -21,7 +21,7 @@
#include "TiffDecode.h" #include "TiffDecode.h"
void dump_state(const TIFFSTATE *state){ void dump_state(const TIFFSTATE *state){
TRACE(("State: Location %u size %d eof %d data: %p \n", (uint)state->loc, TRACE(("State: Location %u size %d eof %d data: %p \n", (uint)state->loc,
(int)state->size, (uint)state->eof, state->data)); (int)state->size, (uint)state->eof, state->data));
} }
@ -32,7 +32,7 @@ void dump_state(const TIFFSTATE *state){
tsize_t _tiffReadProc(thandle_t hdata, tdata_t buf, tsize_t size) { tsize_t _tiffReadProc(thandle_t hdata, tdata_t buf, tsize_t size) {
TIFFSTATE *state = (TIFFSTATE *)hdata; TIFFSTATE *state = (TIFFSTATE *)hdata;
tsize_t to_read; tsize_t to_read;
TRACE(("_tiffReadProc: %d \n", (int)size)); TRACE(("_tiffReadProc: %d \n", (int)size));
dump_state(state); dump_state(state);
@ -49,7 +49,7 @@ tsize_t _tiffReadProc(thandle_t hdata, tdata_t buf, tsize_t size) {
tsize_t _tiffWriteProc(thandle_t hdata, tdata_t buf, tsize_t size) { tsize_t _tiffWriteProc(thandle_t hdata, tdata_t buf, tsize_t size) {
TIFFSTATE *state = (TIFFSTATE *)hdata; TIFFSTATE *state = (TIFFSTATE *)hdata;
tsize_t to_write; tsize_t to_write;
TRACE(("_tiffWriteProc: %d \n", (int)size)); TRACE(("_tiffWriteProc: %d \n", (int)size));
dump_state(state); dump_state(state);
@ -69,7 +69,7 @@ tsize_t _tiffWriteProc(thandle_t hdata, tdata_t buf, tsize_t size) {
} }
state->data = new; state->data = new;
state->size = newsize; state->size = newsize;
to_write = size; to_write = size;
} }
TRACE(("to_write: %d\n", (int)to_write)); TRACE(("to_write: %d\n", (int)to_write));
@ -153,7 +153,7 @@ int ImagingLibTiffInit(ImagingCodecState state, int compression, int fp) {
state->xoff, state->yoff)); state->xoff, state->yoff));
TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes));
TRACE(("State: context %p \n", state->context)); TRACE(("State: context %p \n", state->context));
clientstate->loc = 0; clientstate->loc = 0;
clientstate->size = 0; clientstate->size = 0;
clientstate->data = 0; clientstate->data = 0;
@ -188,12 +188,12 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, int
im->image8, im->image32, im->image, im->block)); im->image8, im->image32, im->image, im->block));
TRACE(("Image: pixelsize: %d, linesize %d \n", TRACE(("Image: pixelsize: %d, linesize %d \n",
im->pixelsize, im->linesize)); im->pixelsize, im->linesize));
dump_state(clientstate); dump_state(clientstate);
clientstate->size = bytes; clientstate->size = bytes;
clientstate->eof = clientstate->size; clientstate->eof = clientstate->size;
clientstate->loc = 0; clientstate->loc = 0;
clientstate->data = (tdata_t)buffer; clientstate->data = (tdata_t)buffer;
clientstate->flrealloc = 0; clientstate->flrealloc = 0;
dump_state(clientstate); dump_state(clientstate);
@ -201,7 +201,7 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, int
TRACE(("Opening using fd: %d\n",clientstate->fp)); TRACE(("Opening using fd: %d\n",clientstate->fp));
lseek(clientstate->fp,0,SEEK_SET); // Sometimes, I get it set to the end. lseek(clientstate->fp,0,SEEK_SET); // Sometimes, I get it set to the end.
tiff = TIFFFdOpen(clientstate->fp, filename, mode); tiff = TIFFFdOpen(clientstate->fp, filename, mode);
} else { } else {
TRACE(("Opening from string\n")); TRACE(("Opening from string\n"));
tiff = TIFFClientOpen(filename, mode, tiff = TIFFClientOpen(filename, mode,
(thandle_t) clientstate, (thandle_t) clientstate,
@ -226,9 +226,9 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, int
} }
// Have to do this row by row and shove stuff into the buffer that way, // Have to do this row by row and shove stuff into the buffer that way,
// with shuffle. (or, just alloc a buffer myself, then figure out how to get it // with shuffle. (or, just alloc a buffer myself, then figure out how to get it
// back in. Can't use read encoded stripe. // back in. Can't use read encoded stripe.
// This thing pretty much requires that I have the whole image in one shot. // This thing pretty much requires that I have the whole image in one shot.
// Prehaps a stub version would work better??? // Prehaps a stub version would work better???
while(state->y < state->ysize){ while(state->y < state->ysize){
@ -240,27 +240,27 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, int
} }
/* TRACE(("Decoded row %d \n", state->y)); */ /* TRACE(("Decoded row %d \n", state->y)); */
state->shuffle((UINT8*) im->image[state->y + state->yoff] + state->shuffle((UINT8*) im->image[state->y + state->yoff] +
state->xoff * im->pixelsize, state->xoff * im->pixelsize,
state->buffer, state->buffer,
state->xsize); state->xsize);
state->y++; state->y++;
} }
TIFFClose(tiff); TIFFClose(tiff);
TRACE(("Done Decoding, Returning \n")); TRACE(("Done Decoding, Returning \n"));
// Returning -1 here to force ImageFile.load to break, rather than // Returning -1 here to force ImageFile.load to break, rather than
// even think about looping back around. // even think about looping back around.
return -1; return -1;
} }
int ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp) { int ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp) {
// Open the FD or the pointer as a tiff file, for writing. // Open the FD or the pointer as a tiff file, for writing.
// We may have to do some monkeying around to make this really work. // We may have to do some monkeying around to make this really work.
// If we have a fp, then we're good. // If we have a fp, then we're good.
// If we have a memory string, we're probably going to have to malloc, then // If we have a memory string, we're probably going to have to malloc, then
// shuffle bytes into the writescanline process. // shuffle bytes into the writescanline process.
// Going to have to deal with the directory as well. // Going to have to deal with the directory as well.
TIFFSTATE *clientstate = (TIFFSTATE *)state->context; TIFFSTATE *clientstate = (TIFFSTATE *)state->context;
int bufsize = 64*1024; int bufsize = 64*1024;
@ -274,7 +274,7 @@ int ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp) {
state->xoff, state->yoff)); state->xoff, state->yoff));
TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes));
TRACE(("State: context %p \n", state->context)); TRACE(("State: context %p \n", state->context));
clientstate->loc = 0; clientstate->loc = 0;
clientstate->size = 0; clientstate->size = 0;
clientstate->eof =0; clientstate->eof =0;
@ -298,7 +298,7 @@ int ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp) {
TRACE(("Error, couldn't allocate a buffer of size %d\n", bufsize)); TRACE(("Error, couldn't allocate a buffer of size %d\n", bufsize));
return 0; return 0;
} }
clientstate->tiff = TIFFClientOpen(filename, mode, clientstate->tiff = TIFFClientOpen(filename, mode,
(thandle_t) clientstate, (thandle_t) clientstate,
_tiffReadProc, _tiffWriteProc, _tiffReadProc, _tiffWriteProc,
@ -310,7 +310,7 @@ int ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp) {
if (!clientstate->tiff) { if (!clientstate->tiff) {
TRACE(("Error, couldn't open tiff file\n")); TRACE(("Error, couldn't open tiff file\n"));
return 0; return 0;
} }
return 1; return 1;
@ -318,7 +318,7 @@ int ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp) {
int ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...){ int ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...){
// after tif_dir.c->TIFFSetField. // after tif_dir.c->TIFFSetField.
TIFFSTATE *clientstate = (TIFFSTATE *)state->context; TIFFSTATE *clientstate = (TIFFSTATE *)state->context;
va_list ap; va_list ap;
int status; int status;
@ -331,17 +331,17 @@ int ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...){
int ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8* buffer, int bytes) { int ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8* buffer, int bytes) {
/* One shot encoder. Encode everything to the tiff in the clientstate. /* One shot encoder. Encode everything to the tiff in the clientstate.
If we're running off of a FD, then run once, we're good, everything If we're running off of a FD, then run once, we're good, everything
ends up in the file, we close and we're done. ends up in the file, we close and we're done.
If we're going to memory, then we need to write the whole file into memory, then If we're going to memory, then we need to write the whole file into memory, then
parcel it back out to the pystring buffer bytes at a time. parcel it back out to the pystring buffer bytes at a time.
*/ */
TIFFSTATE *clientstate = (TIFFSTATE *)state->context; TIFFSTATE *clientstate = (TIFFSTATE *)state->context;
TIFF *tiff = clientstate->tiff; TIFF *tiff = clientstate->tiff;
TRACE(("in encoder: bytes %d\n", bytes)); TRACE(("in encoder: bytes %d\n", bytes));
TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state, TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state,
state->x, state->y, state->ystep)); state->x, state->y, state->ystep));
@ -358,12 +358,12 @@ int ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8* buffer, int
im->pixelsize, im->linesize)); im->pixelsize, im->linesize));
dump_state(clientstate); dump_state(clientstate);
if (state->state == 0) { if (state->state == 0) {
TRACE(("Encoding line bt line")); TRACE(("Encoding line bt line"));
while(state->y < state->ysize){ while(state->y < state->ysize){
state->shuffle(state->buffer, state->shuffle(state->buffer,
(UINT8*) im->image[state->y + state->yoff] + (UINT8*) im->image[state->y + state->yoff] +
state->xoff * im->pixelsize, state->xoff * im->pixelsize,
state->xsize); state->xsize);
@ -377,7 +377,7 @@ int ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8* buffer, int
return -1; return -1;
} }
state->y++; state->y++;
} }
if (state->y == state->ysize) { if (state->y == state->ysize) {
state->state=1; state->state=1;
@ -392,7 +392,7 @@ int ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8* buffer, int
free(clientstate->data); free(clientstate->data);
} }
return -1; return -1;
} }
TRACE(("Closing \n")); TRACE(("Closing \n"));
TIFFClose(tiff); TIFFClose(tiff);
// reset the clientstate metadata to use it to read out the buffer. // reset the clientstate metadata to use it to read out the buffer.

View File

@ -46,7 +46,7 @@ extern int ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...);
#if defined(_MSC_VER) && (_MSC_VER == 1310) #if defined(_MSC_VER) && (_MSC_VER == 1310)
/* VS2003/py2.4 can't use varargs. Skipping trace for now.*/ /* VS2003/py2.4 can't use varargs. Skipping trace for now.*/
#define TRACE(args) #define TRACE(args)
#else #else
/* /*
@ -60,4 +60,4 @@ extern int ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...);
#endif #endif

View File

@ -27,7 +27,7 @@ typedef struct {
/* Optimize (max compression) SLOW!!! */ /* Optimize (max compression) SLOW!!! */
int optimize; int optimize;
/* 0 no compression, 9 best compression, -1 default compression */ /* 0 no compression, 9 best compression, -1 default compression */
int compress_level; int compress_level;
/* compression strategy Z_XXX */ /* compression strategy Z_XXX */
@ -54,9 +54,9 @@ typedef struct {
UINT8* output; /* output data */ UINT8* output; /* output data */
int prefix; /* size of filter prefix (0 for TIFF data) */ int prefix; /* size of filter prefix (0 for TIFF data) */
int interlaced; /* is the image interlaced? (PNG) */ int interlaced; /* is the image interlaced? (PNG) */
int pass; /* current pass of the interlaced image (PNG) */ int pass; /* current pass of the interlaced image (PNG) */
} ZIPSTATE; } ZIPSTATE;

View File

@ -32,7 +32,7 @@ static const int ROW_INCREMENT[] = { 8, 8, 8, 4, 4, 2, 2 };
* for interlaced images */ * for interlaced images */
static int get_row_len(ImagingCodecState state, int pass) static int get_row_len(ImagingCodecState state, int pass)
{ {
int row_len = (state->xsize + OFFSET[pass]) / COL_INCREMENT[pass]; int row_len = (state->xsize + OFFSET[pass]) / COL_INCREMENT[pass];
return ((row_len * state->bits) + 7) / 8; return ((row_len * state->bits) + 7) / 8;
} }
@ -202,7 +202,7 @@ ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
if (state->bits >= 8) { if (state->bits >= 8) {
/* Stuff pixels in their correct location, one by one */ /* Stuff pixels in their correct location, one by one */
for (i = 0; i < row_len; i += ((state->bits + 7) / 8)) { for (i = 0; i < row_len; i += ((state->bits + 7) / 8)) {
state->shuffle((UINT8*) im->image[state->y] + state->shuffle((UINT8*) im->image[state->y] +
col * im->pixelsize, col * im->pixelsize,
state->buffer + context->prefix + i, 1); state->buffer + context->prefix + i, 1);
col += COL_INCREMENT[context->pass]; col += COL_INCREMENT[context->pass];
@ -214,7 +214,7 @@ ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
for (i = 0; i < row_bits; i += state->bits) { for (i = 0; i < row_bits; i += state->bits) {
UINT8 byte = *(state->buffer + context->prefix + (i / 8)); UINT8 byte = *(state->buffer + context->prefix + (i / 8));
byte <<= (i % 8); byte <<= (i % 8);
state->shuffle((UINT8*) im->image[state->y] + state->shuffle((UINT8*) im->image[state->y] +
col * im->pixelsize, &byte, 1); col * im->pixelsize, &byte, 1);
col += COL_INCREMENT[context->pass]; col += COL_INCREMENT[context->pass];
} }
@ -235,7 +235,7 @@ ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
memset(state->buffer, 0, state->bytes+1); memset(state->buffer, 0, state->bytes+1);
} }
} else { } else {
state->shuffle((UINT8*) im->image[state->y + state->yoff] + state->shuffle((UINT8*) im->image[state->y + state->yoff] +
state->xoff * im->pixelsize, state->xoff * im->pixelsize,
state->buffer + context->prefix, state->buffer + context->prefix,
state->xsize); state->xsize);

View File

@ -156,7 +156,7 @@ ImagingZipEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
/* Stuff image data into the compressor */ /* Stuff image data into the compressor */
state->shuffle(state->buffer+1, state->shuffle(state->buffer+1,
(UINT8*) im->image[state->y + state->yoff] + (UINT8*) im->image[state->y + state->yoff] +
state->xoff * im->pixelsize, state->xoff * im->pixelsize,
state->xsize); state->xsize);

14
map.c
View File

@ -130,7 +130,7 @@ mapping_dealloc(ImagingMapperObject* mapper)
/* -------------------------------------------------------------------- */ /* -------------------------------------------------------------------- */
/* standard file operations */ /* standard file operations */
static PyObject* static PyObject*
mapping_read(ImagingMapperObject* mapper, PyObject* args) mapping_read(ImagingMapperObject* mapper, PyObject* args)
{ {
PyObject* buf; PyObject* buf;
@ -157,7 +157,7 @@ mapping_read(ImagingMapperObject* mapper, PyObject* args)
return buf; return buf;
} }
static PyObject* static PyObject*
mapping_seek(ImagingMapperObject* mapper, PyObject* args) mapping_seek(ImagingMapperObject* mapper, PyObject* args)
{ {
int offset; int offset;
@ -195,7 +195,7 @@ ImagingDestroyMap(Imaging im)
return; /* nothing to do! */ return; /* nothing to do! */
} }
static PyObject* static PyObject*
mapping_readimage(ImagingMapperObject* mapper, PyObject* args) mapping_readimage(ImagingMapperObject* mapper, PyObject* args)
{ {
int y, size; int y, size;
@ -244,7 +244,7 @@ mapping_readimage(ImagingMapperObject* mapper, PyObject* args)
if (!ImagingNewEpilogue(im)) if (!ImagingNewEpilogue(im))
return NULL; return NULL;
mapper->offset += size; mapper->offset += size;
return PyImagingNew(im); return PyImagingNew(im);
} }
@ -292,7 +292,7 @@ static PyTypeObject ImagingMapperType = {
0, /*tp_getset*/ 0, /*tp_getset*/
}; };
PyObject* PyObject*
PyImaging_Mapper(PyObject* self, PyObject* args) PyImaging_Mapper(PyObject* self, PyObject* args)
{ {
char* filename; char* filename;
@ -315,12 +315,12 @@ static void
mapping_destroy_buffer(Imaging im) mapping_destroy_buffer(Imaging im)
{ {
ImagingBufferInstance* buffer = (ImagingBufferInstance*) im; ImagingBufferInstance* buffer = (ImagingBufferInstance*) im;
PyBuffer_Release(&buffer->view); PyBuffer_Release(&buffer->view);
Py_XDECREF(buffer->target); Py_XDECREF(buffer->target);
} }
PyObject* PyObject*
PyImaging_MapBuffer(PyObject* self, PyObject* args) PyImaging_MapBuffer(PyObject* self, PyObject* args)
{ {
int y, size; int y, size;

4
path.c
View File

@ -119,7 +119,7 @@ PyPath_Flatten(PyObject* data, double **pxy)
*pxy = xy; *pxy = xy;
return path->count; return path->count;
} }
if (PyImaging_CheckBuffer(data)) { if (PyImaging_CheckBuffer(data)) {
/* Assume the buffer contains floats */ /* Assume the buffer contains floats */
Py_buffer buffer; Py_buffer buffer;
@ -380,7 +380,7 @@ path_getslice(PyPathObject* self, Py_ssize_t ilow, Py_ssize_t ihigh)
ihigh = ilow; ihigh = ilow;
else if (ihigh > self->count) else if (ihigh > self->count)
ihigh = self->count; ihigh = self->count;
return (PyObject*) path_new(ihigh - ilow, self->xy + ilow * 2, 1); return (PyObject*) path_new(ihigh - ilow, self->xy + ilow * 2, 1);
} }