Fredrik Lundh avatar Fredrik Lundh committed 7094281 Merge

Reopen cms branch.

Comments (0)

Files changed (30)

-770a9717f387cb878fc44b0e9be88e677b9abcd3 pil-116
+770a9717f387cb878fc44b0e9be88e677b9abcd3 pil-116
+7493ffdf4aff81dfcf263ea90688f7ae81ae02a7 pil-117-20090309
 
 *** Changes from release 1.1.6 to 1.1.7 ***
 
-+ Fixed OverflowError when reading top-to-bottom BMP images (reported
-  by Wichert Akkerman, who also provided samples).
+FIXME: This section will be updated before the first alpha.  For now,
+see the repository revision history, available here:
 
-+ Fixed JPEG CMYK handling (from Kevin Cazabon and Paul Egan).
-
-+ Added resolution save option for PDF files (from Andreas Kostyrka).
-
-+ Look for Tcl/Tk files in /usr/include/tclX.X (from Encolpe Degoute)
-
-+ Fixed rounding error in ImageColor.getcolor("L") (from Tim Hatch).
-
-+ Fixed truetype positioning when first character has a negative left
-  bearing (from Ned Batchelder).
-
-+ Fixed resolution unit bug in Tiff reader/writer (based on patches
-  by Gary Bloom and Florian H�ch)
-
-+ Handle simple PNG transparency also for RGB files (via the
-  transparency info attribute and save option).  (reported by
-  Sebastian Spaeth).
-
-+ Added support for Unicode for truetype filenames (reported by Donn
-  Ingle)
-
-+ Fixed crash in ImageFont's getname() method when the font file has
-  no style information (from Donn Ingle)
-
-+ Fixed encoding issue in PIL/WalImageFile.py (from Santiago M. Mola)
+  http://bitbucket.org/effbot/pil-2009-raclette/changesets/
 
 *** Changes from release 1.1.5 to 1.1.6 ***
 
 
         self.load()
 
+        if isinstance(lut, ImagePointHandler):
+            return lut.point(self)
+
         if not isSequenceType(lut):
             # if it isn't a list, it should be a function
             if self.mode in ("I", "I;16", "F"):
     def transform(self, size, method, data=None, resample=NEAREST, fill=1):
         "Transform image"
 
+        if isinstance(method, ImageTransformHandler):
+            return method.transform(size, self, resample=resample, fill=fill)
         if hasattr(method, "getdata"):
+            # compatibility w. old-style transform objects
             method, data = method.getdata()
         if data is None:
             raise ValueError("missing method data")
         # sequences!
 
 # --------------------------------------------------------------------
+# Abstract handlers.
+
+class ImagePointHandler:
+    # used as a mixin by point transforms (for use with im.point)
+    pass
+
+class ImageTransformHandler:
+    # used as a mixin by geometry transforms (for use with im.transform)
+    pass
+
+# --------------------------------------------------------------------
 # Factories
 
 #
 
     Version History:
 
+        0.1.0 pil mod   March 10, 2009
+
+                        Renamed display profile to proof profile. The proof
+                        profile is the profile of the device that is being
+                        simulated, not the profile of the device which is
+                        actually used to display/print the final simulation
+                        (that'd be the output profile) - also see LCMSAPI.txt
+                        input colorspace -> using 'renderingIntent' -> proof
+                        colorspace -> using 'proofRenderingIntent' -> output
+                        colorspace
+
+                        Added LCMS FLAGS support.
+                        Added FLAGS["SOFTPROOFING"] as default flag for
+                        buildProofTransform (otherwise the proof profile/intent
+                        would be ignored).
+
         0.1.0 pil       March 2009 - added to PIL, as PIL.ImageCms
 
         0.0.2 alpha     Jan 6, 2002
-        
+
                         Added try/except statements arount type() checks of
                         potential CObjects... Python won't let you use type()
                         on them, and raises a TypeError (stupid, if you ask me!)
 
-                        Added buildProofTransformFromOpenProfiles() function.                        
+                        Added buildProofTransformFromOpenProfiles() function.
                         Additional fixes in DLL, see DLL code for details.
-                        
+
         0.0.1 alpha     first public release, Dec. 26, 2002
 
     Known to-do list with current version (of Python interface, not pyCMSdll):
 
         none
-      
+
 """
 
 VERSION = "0.1.0 pil"
 DIRECTION_OUTPUT = 1
 DIRECTION_PROOF = 2
 
+#
+# flags
+
+FLAGS = {
+    "MATRIXINPUT": 1,
+    "MATRIXOUTPUT": 2,
+    "MATRIXONLY": (1|2),
+    "NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot
+    "NOPRELINEARIZATION": 16, # Don't create prelinearization tables on precalculated transforms (internal use)
+    "GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink)
+    "NOTCACHE": 64, # Inhibit 1-pixel cache
+    "NOTPRECALC": 256,
+    "NULLTRANSFORM": 512, # Don't transform anyway
+    "HIGHRESPRECALC": 1024, # Use more memory to give better accurancy
+    "LOWRESPRECALC": 2048, # Use less memory to minimize resouces
+    "WHITEBLACKCOMPENSATION": 8192,
+    "BLACKPOINTCOMPENSATION": 8192,
+    "GAMUTCHECK": 4096, # Out of Gamut alarm
+    "SOFTPROOFING": 16384, # Do softproofing
+    "PRESERVEBLACK": 32768, # Black preservation
+    "NODEFAULTRESOURCEDEF": 16777216, # CRD special
+    "GRIDPOINTS": lambda n: ((n) & 0xFF) << 16 # Gridpoints
+}
+
+# --------------------------------------------------------------------.
+# Experimental PIL-level API
+# --------------------------------------------------------------------.
+
+##
+# Profile.
+
+class ImageCmsProfile:
+
+    def __init__(self, profile):
+        # accepts a string (filename), a file-like object, or a low-level
+        # profile object
+        if Image.isStringType(profile):
+            self._set(cmscore.profile_open(profile))
+        elif hasattr(profile, "read"):
+            self._set(cmscore.profile_fromstring(profile.read()))
+        else:
+            self._set(profile) # assume it's already a profile
+
+    def _set(self, profile):
+        self.profile = profile
+        if profile:
+            self.product_name = profile.product_name
+            self.product_info = profile.product_info
+        else:
+            self.product_name = None
+            self.product_info = None
+
+##
+# Transform.  This can be used with the procedural API, or with the
+# standard {@link Image.point} method.
+
+class ImageCmsTransform(Image.ImagePointHandler):
+
+    def __init__(self, input, output, input_mode, output_mode,
+                 intent=INTENT_PERCEPTUAL,
+                 proof=None, proof_intent=INTENT_ABSOLUTE_COLORIMETRIC, flags=0):
+        if proof is None:
+            self.transform = cmscore.buildTransform(
+                input.profile, output.profile,
+                input_mode, output_mode,
+                intent,
+                flags
+                )
+        else:
+            self.transform = cmscore.buildProofTransform(
+                input.profile, output.profile, proof.profile,
+                input_mode, output_mode,
+                intent, proof_intent,
+                flags
+                )
+        # Note: inputMode and outputMode are for pyCMS compatibility only
+        self.input_mode = self.inputMode = input_mode
+        self.output_mode = self.outputMode = output_mode
+
+    def point(self, im):
+        return self.apply(im)
+
+    def apply(self, im, imOut=None):
+        im.load()
+        if imOut is None:
+            imOut = Image.new(self.output_mode, im.size, None)
+        result = self.transform.apply(im.im.id, imOut.im.id)
+        return imOut
+
+    def apply_in_place(self, im):
+        im.load()
+        if im.mode != self.output_mode:
+            raise ValueError("mode mismatch") # wrong output mode
+        result = self.transform.apply(im.im.id, im.im.id)
+        return im
+
 # --------------------------------------------------------------------.
 # pyCMS compatible layer
 # --------------------------------------------------------------------.
 
-def _make_profile(profile):
-    if Image.isStringType(profile):
-        return cmscore.profile_open(profile)
-    if hasattr(profile, "read"):
-        return cmscore.profile_fromstring(profile.read())
-    return profile # assume it's already a profile
-
 ##
-# Exception class.  This is used for all errors in the pyCMS API.
+# (pyCMS) Exception class.  This is used for all errors in the pyCMS API.
 
 class PyCMSError(Exception):
     pass
 
 ##
-# Applies an ICC transformation to a given image, mapping from
+# (pyCMS) Applies an ICC transformation to a given image, mapping from
 # inputProfile to outputProfile.
 
-def profileToProfile(im, inputProfile, outputProfile, renderingIntent=INTENT_PERCEPTUAL, outputMode=None, inPlace=0):
+def profileToProfile(im, inputProfile, outputProfile, renderingIntent=INTENT_PERCEPTUAL, outputMode=None, inPlace=0, flags=0):
     """
     ImageCms.profileToProfile(im, inputProfile, outputProfile,
         [renderingIntent], [outputMode], [inPlace])
-        
+
     Returns either None or a new PIL image object, depending on value of
-    inPlace (see below).  
+    inPlace (see below).
 
     im = an open PIL image object (i.e. Image.new(...) or
         Image.open(...), etc.)
         image is modified in-place, and None is returned.  If FALSE
         (default), a new Image object is returned with the transform
         applied.
+    flags = integer (0-...) specifying additional flags
 
     If the input or output profiles specified are not valid filenames, a
     PyCMSError will be raised.  If inPlace == TRUE and outputMode != im.mode,
     profiles, the input profile must handle RGB data, and the output
     profile must handle CMYK data.
 
-    """    
-    
+    """
+
     if outputMode is None:
         outputMode = im.mode
 
     if type(renderingIntent) != type(1) or not (0 <= renderingIntent <=3):
         raise PyCMSError("renderingIntent must be an integer between 0 and 3")
 
-    if inPlace and im.mode != outputMode:
-        raise PyCMSError("Cannot transform image in place, im.mode and output mode are different (%s vs. %s)" % (im.mode, outputMode))
-
-    if inPlace:
-        imOut = im
-        if imOut.readonly:
-            imOut._copy()
-    else:
-        imOut = Image.new(outputMode, im.size)
-
-    im.load() # make sure it's loaded, or it may not have a .im attribute!
+    flagsum = sum([flag if type(flag) == type(1) else 0 for flag in FLAGS.values()])
+    if type(flags) != type(1) or not (0 <= flags <=flagsum):
+        raise PyCMSError("flags must be an integer between 0 and " + flagsum)
 
     try:
-        result = cmscore.profileToProfile(im.im.id, imOut.im.id, inputProfile, outputProfile, renderingIntent)
+        if not isinstance(inputProfile, ImageCmsProfile):
+            inputProfile = ImageCmsProfile(inputProfile)
+        if not isinstance(outputProfile, ImageCmsProfile):
+            outputProfile = ImageCmsProfile(outputProfile)
+        transform = ImageCmsTransform(
+            inputProfile, outputProfile, im.mode, outputMode, renderingIntent, flags=flags
+            )
+        if inPlace:
+            transform.apply_in_place(im)
+            imOut = None
+        else:
+            imOut = transform.apply(im)
     except (IOError, TypeError, ValueError), v:
         raise PyCMSError(v)
 
-    if result == 0:
-        if inPlace:
-            return None
-        else:
-            return imOut
-
-    elif result == -1:
-        raise PyCMSError("Error occurred in _imagingcms.profileToProfile()")
-    else:
-        raise PyCMSError(result)
+    return imOut
 
 ##
-# Opens an ICC profile file.
+# (pyCMS) Opens an ICC profile file.
 
 def getOpenProfile(profileFilename):
     """
     ImageCms.getOpenProfile(profileFilename)
-    
-    Returns a CmsProfile class object.  
+
+    Returns a CmsProfile class object.
 
     profileFilename = string, as a valid filename path to the ICC profile
-        you wish to open
+        you wish to open, or a file-like object.
 
     The PyCMSProfile object can be passed back into pyCMS for use in creating
     transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
 
     If profileFilename is not a vaild filename for an ICC profile, a
-    PyCMSError will be raised.    
+    PyCMSError will be raised.
 
-    """    
-    
+    """
+
     try:
-        return cmscore.profile_open(profileFilename)
+        return ImageCmsProfile(profileFilename)
     except (IOError, TypeError, ValueError), v:
         raise PyCMSError(v)
 
 ##
-# Creates an ICC profile from data in a buffer.
+# (pyCMS) Builds an ICC transform mapping from the inputProfile to the
+# outputProfile.  Use applyTransform to apply the transform to a given
+# image.
 
-def getMemoryProfile(buffer):
-    try:
-        return cmscore.profile_fromstring(buffer)
-    except (IOError, TypeError, ValueError), v:
-        raise PyCMSError(v)
-
-##
-# Builds an ICC transform mapping from the inputProfile to the
-# outputProfile.  Use applyTransform to apply the transform to
-# a given image.
-
-def buildTransform(inputProfile, outputProfile, inMode, outMode, renderingIntent=INTENT_PERCEPTUAL):
+def buildTransform(inputProfile, outputProfile, inMode, outMode, renderingIntent=INTENT_PERCEPTUAL, flags=0):
     """
     ImageCms.buildTransform(inputProfile, outputProfile, inMode, outMode,
         [renderingIntent])
-        
+
     Returns a CmsTransform class object.
-    
+
     inputProfile = string, as a valid filename path to the ICC input
         profile you wish to use for this transform, or a profile object
     outputProfile = string, as a valid filename path to the ICC output
         INTENT_ABSOLUTE_COLORIMETRIC =3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)
         see the pyCMS documentation for details on rendering intents and
         what they do.
+    flags = integer (0-...) specifying additional flags
 
     If the input or output profiles specified are not valid filenames, a
     PyCMSError will be raised.  If an error occurs during creation of the
     transform, a PyCMSError will be raised.
-    
+
     If inMode or outMode are not a mode supported by the outputProfile (or
     by pyCMS), a PyCMSError will be raised.
 
     manually overridden if you really want to, but I don't know of any
     time that would be of use, or would even work).
 
-    """   
+    """
 
     if type(renderingIntent) != type(1) or not (0 <= renderingIntent <=3):
         raise PyCMSError("renderingIntent must be an integer between 0 and 3")
 
-    inputProfile = _make_profile(inputProfile)
-    outputProfile = _make_profile(outputProfile)
+    flagsum = sum([flag if type(flag) == type(1) else 0 for flag in FLAGS.values()])
+    if type(flags) != type(1) or not (0 <= flags <=flagsum):
+        raise PyCMSError("flags must be an integer between 0 and " + flagsum)
 
     try:
-        return cmscore.buildTransform(inputProfile, outputProfile, inMode, outMode, renderingIntent)
+        if not isinstance(inputProfile, ImageCmsProfile):
+            inputProfile = ImageCmsProfile(inputProfile)
+        if not isinstance(outputProfile, ImageCmsProfile):
+            outputProfile = ImageCmsProfile(outputProfile)
+        return ImageCmsTransform(inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags)
     except (IOError, TypeError, ValueError), v:
         raise PyCMSError(v)
 
 ##
-# Builds an ICC transform mapping from the inputProfile to the
-# displayProfile, but tries to simulate the result that would be
-# obtained on the outputProfile device.
+# (pyCMS) Builds an ICC transform mapping from the inputProfile to the
+# outputProfile, but tries to simulate the result that would be
+# obtained on the proofProfile device.
 
-def buildProofTransform(inputProfile, outputProfile, displayProfile, inMode, outMode, renderingIntent=INTENT_PERCEPTUAL, displayRenderingIntent=INTENT_PERCEPTUAL):
+def buildProofTransform(inputProfile, outputProfile, proofProfile, inMode, outMode, renderingIntent=INTENT_PERCEPTUAL, proofRenderingIntent=INTENT_ABSOLUTE_COLORIMETRIC, flags=FLAGS["SOFTPROOFING"]):
     """
-    ImageCms.buildProofTransform(inputProfile, outputProfile, displayProfile,
-        inMode, outMode, [renderingIntent], [displayRenderingIntent])
-        
+    ImageCms.buildProofTransform(inputProfile, outputProfile, proofProfile,
+        inMode, outMode, [renderingIntent], [proofRenderingIntent])
+
     Returns a CmsTransform class object.
-    
+
     inputProfile = string, as a valid filename path to the ICC input
         profile you wish to use for this transform, or a profile object
     outputProfile = string, as a valid filename path to the ICC output
-        profile you wish to use for this transform, or a profile object
-    displayProfile = string, as a valid filename path to the ICC display
         (monitor, usually) profile you wish to use for this transform,
         or a profile object
+    proofProfile = string, as a valid filename path to the ICC proof
+        profile you wish to use for this transform, or a profile object
     inMode = string, as a valid PIL mode that the appropriate profile also
         supports (i.e. "RGB", "RGBA", "CMYK", etc.)
     outMode = string, as a valid PIL mode that the appropriate profile also
         supports (i.e. "RGB", "RGBA", "CMYK", etc.)
     renderingIntent = integer (0-3) specifying the rendering intent you
-        wish to use for the input->output (simulated) transform
+        wish to use for the input->proof (simulated) transform
         INTENT_PERCEPTUAL =           0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL)
         INTENT_RELATIVE_COLORIMETRIC =1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC)
         INTENT_SATURATION =           2 (ImageCms.INTENT_SATURATION)
         INTENT_ABSOLUTE_COLORIMETRIC =3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)
         see the pyCMS documentation for details on rendering intents and
         what they do.
-    displayRenderingIntent = integer (0-3) specifying the rendering intent
-        you wish to use for (input/output simulation)->display transform
+    proofRenderingIntent = integer (0-3) specifying the rendering intent
+        you wish to use for proof->output transform
         INTENT_PERCEPTUAL =           0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL)
         INTENT_RELATIVE_COLORIMETRIC =1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC)
         INTENT_SATURATION =           2 (ImageCms.INTENT_SATURATION)
         INTENT_ABSOLUTE_COLORIMETRIC =3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)
         see the pyCMS documentation for details on rendering intents and
         what they do.
-        
-    If the input, output, or display profiles specified are not valid
+    flags = integer (0-...) specifying additional flags
+
+    If the input, output, or proof profiles specified are not valid
     filenames, a PyCMSError will be raised.
-    
+
     If an error occurs during creation of the transform, a PyCMSError will
     be raised.
-    
+
     If inMode or outMode are not a mode supported by the outputProfile
     (or by pyCMS), a PyCMSError will be raised.
 
     This function builds and returns an ICC transform from the inputProfile
-    to the displayProfile, but tries to simulate the result that would be
-    obtained on the outputProfile device using renderingIntent and
-    displayRenderingIntent to determine what to do with out-of-gamut
+    to the outputProfile, but tries to simulate the result that would be
+    obtained on the proofProfile device using renderingIntent and
+    proofRenderingIntent to determine what to do with out-of-gamut
     colors.  This is known as "soft-proofing".  It will ONLY work for
     converting images that are in inMode to images that are in outMode
     color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
     Usage of the resulting transform object is exactly the same as with
     ImageCms.buildTransform().
 
-    Proof profiling is generally used when using a "proof" device to get a
+    Proof profiling is generally used when using an output device to get a
     good idea of what the final printed/displayed image would look like on
-    the outputProfile device when it's quicker and easier to use the
-    display device for judging color.  Generally, this means that
-    displayDevice is a monitor, or a dye-sub printer (etc.), and the output
+    the proofProfile device when it's quicker and easier to use the
+    output device for judging color.  Generally, this means that the
+    output device is a monitor, or a dye-sub printer (etc.), and the simulated
     device is something more expensive, complicated, or time consuming
     (making it difficult to make a real print for color judgement purposes).
 
-    Soft-proofing basically functions by limiting the color gamut on the
-    display device to the gamut availabile on the output device.  However,
-    when the final output device has a much wider gamut than the display
+    Soft-proofing basically functions by adjusting the colors on the
+    output device to match the colors of the device being simulated. However,
+    when the simulated device has a much wider gamut than the output
     device, you may obtain marginal results.
-    
-    """ 
+
+    """
 
     if type(renderingIntent) != type(1) or not (0 <= renderingIntent <=3):
         raise PyCMSError("renderingIntent must be an integer between 0 and 3")
 
-    inputProfile = _make_profile(inputProfile)
-    outputProfile = _make_profile(outputProfile)
-    displayProfile = _make_profile(displayProfile)
+    flagsum = sum([flag if type(flag) == type(1) else 0 for flag in FLAGS.values()])
+    if type(flags) != type(1) or not (0 <= flags <=flagsum):
+        raise PyCMSError("flags must be an integer between 0 and " + flagsum)
 
     try:
-        return cmscore.buildProofTransform(inputProfile, outputProfile, displayProfile, inMode, outMode, renderingIntent, displayRenderingIntent)
+        if not isinstance(inputProfile, ImageCmsProfile):
+            inputProfile = ImageCmsProfile(inputProfile)
+        if not isinstance(outputProfile, ImageCmsProfile):
+            outputProfile = ImageCmsProfile(outputProfile)
+        if not isinstance(proofProfile, ImageCmsProfile):
+            proofProfile = ImageCmsProfile(proofProfile)
+        return ImageCmsTransform(inputProfile, outputProfile, inMode, outMode, renderingIntent, proofProfile, proofRenderingIntent, flags)
     except (IOError, TypeError, ValueError), v:
         raise PyCMSError(v)
 
 buildProofTransformFromOpenProfiles = buildProofTransform
 
 ##
-# Applies a transform to a given image.
+# (pyCMS) Applies a transform to a given image.
 
 def applyTransform(im, transform, inPlace=0):
     """
     ImageCms.applyTransform(im, transform, [inPlace])
-    
+
     Returns either None, or a new PIL Image object, depending on the value
         of inPlace (see below)
 
         changed).  The default is FALSE.
 
     If im.mode != transform.inMode, a PyCMSError is raised.
-    
+
     If inPlace == TRUE and transform.inMode != transform.outMode, a
     PyCMSError is raised.
-    
+
     If im.mode, transfer.inMode, or transfer.outMode is not supported by
     pyCMSdll or the profiles you used for the transform, a PyCMSError is
     raised.
-    
+
     If an error occurs while the transform is being applied, a PyCMSError
     is raised.
 
     different).  The  default behavior is to return a new Image object of
     the same dimensions in mode transform.outMode.
 
-    """  
+    """
 
-    if im.mode != transform.inputMode:
-        raise PyCMSError("Image mode does not match profile input mode (%s vs %s)" % (im.mode, transform.inputMode))
-    
-    if inPlace:
-        if transform.inputMode != transform.outputMode:
-            raise PyCMSError("Cannot transform image in place, input mode and output mode are different (%s vs. %s)" % (transform.inputMode, transform.outputMode))
-        imOut = im
-        if imOut.readonly:
-            imOut._copy()
-    else:
-        imOut = Image.new(transform.outputMode, im.size)
-
-    im.load() #make sure it's loaded, or it may not have an .im attribute!
-    
     try:
-        result = cmscore.applyTransform(im.im.id, imOut.im.id, transform)
+        if inPlace:
+            transform.apply_in_place(im)
+            imOut = None
+        else:
+            imOut = transform.apply(im)
     except (TypeError, ValueError), v:
         raise PyCMSError(v)
 
-    if result == 0:
-        if inPlace:
-            return None
-        else:
-            return imOut
-
-    elif result == -1:
-        raise PyCMSError("Error occurred in _imagingcms.applyTransform()")
-    else:
-        raise PyCMSError(result)
+    return imOut
 
 ##
-# Creates a profile.
+# (pyCMS) Creates a profile.
 
 def createProfile(colorSpace, colorTemp=-1):
     """
     ImageCms.createProfile(colorSpace, [colorTemp])
-    
+
     Returns a CmsProfile class object
 
     colorSpace = string, the color space of the profile you wish to create.
         LAB profiles, and is ignored for XYZ and sRGB.
 
     If colorSpace not in ["LAB", "XYZ", "sRGB"], a PyCMSError is raised
-    
+
     If using LAB and colorTemp != a positive integer, a PyCMSError is raised.
-    
+
     If an error occurs while creating the profile, a PyCMSError is raised.
 
     Use this function to create common profiles on-the-fly instead of
     ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
     to images.
 
-    """    
+    """
     if colorSpace not in ["LAB", "XYZ", "sRGB"]:
         raise PyCMSError("Color space not supported for on-the-fly profile creation (%s)" % colorSpace)
 
             colorTemp = int(colorTemp + 0.5)
         if type (colorTemp) != type (5000):
             raise PyCMSError("Color temperature must be a positive integer, \"%s\" not valid" % colorTemp)
-        
+
     try:
         return cmscore.createProfile(colorSpace, colorTemp)
     except (TypeError, ValueError), v:
         raise PyCMSError(v)
 
 ##
-# Gets the internal product name for the given profile.
+# (pyCMS) Gets the internal product name for the given profile.
 
 def getProfileName(profile):
     """
     ImageCms.getProfileName(profile)
-    
+
     Returns a string containing the internal name of the profile as stored
         in an ICC tag.
 
     in an ICC tag in the profile itself), usually the one used when the
     profile was originally created.  Sometimes this tag also contains
     additional information supplied by the creator.
-    
+
     """
     try:
         # add an extra newline to preserve pyCMS compatibility
-        return _make_profile(profile).product_name + "\n"
+        if not isinstance(profile, ImageCmsProfile):
+            profile = ImageCmsProfile(profile)
+        return profile.profile.product_name + "\n"
     except (AttributeError, IOError, TypeError, ValueError), v:
         raise PyCMSError(v)
 
 ##
-# Gets the internal product information for the given profile.
+# (pyCMS) Gets the internal product information for the given profile.
 
 def getProfileInfo(profile):
     """
     ImageCms.getProfileInfo(profile)
-    
+
     Returns a string containing the internal profile information stored in
         an ICC tag.
 
 
     """
     try:
+        if not isinstance(profile, ImageCmsProfile):
+            profile = ImageCmsProfile(profile)
         # add an extra newline to preserve pyCMS compatibility
-        return _make_profile(profile).product_info + "\n"
+        return profile.product_info + "\n"
     except (AttributeError, IOError, TypeError, ValueError), v:
         raise PyCMSError(v)
 
 ##
-# Gets the default intent name for the given profile.
+# (pyCMS) Gets the default intent name for the given profile.
 
 def getDefaultIntent(profile):
     """
     ImageCms.getDefaultIntent(profile)
-    
+
     Returns integer 0-3 specifying the default rendering intent for this
         profile.
         INTENT_PERCEPTUAL =           0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL)
 
     profile = EITHER a valid CmsProfile object, OR a string of the
         filename of an ICC profile.
-    
+
     If profile isn't a valid CmsProfile object or filename to a profile,
     a PyCMSError is raised.
-    
+
     If an error occurs while trying to obtain the default intent, a
     PyCMSError is raised.
 
     rendering intents, but are intended mostly for one type of conversion.
     If you wish to use a different intent than returned, use
     ImageCms.isIntentSupported() to verify it will work first.
-    """    
+    """
     try:
-        return _make_profile(profile).rendering_intent
+        if not isinstance(profile, ImageCmsProfile):
+            profile = ImageCmsProfile(profile)
+        return profile.profile.rendering_intent
     except (AttributeError, IOError, TypeError, ValueError), v:
         raise PyCMSError(v)
 
 ##
-# Checks if a given intent is supported.
+# (pyCMS) Checks if a given intent is supported.
 
 def isIntentSupported(profile, intent, direction):
     """
     ImageCms.isIntentSupported(profile, intent, direction)
-    
+
     Returns 1 if the intent/direction are supported, -1 if they are not.
 
     profile = EITHER a valid CmsProfile object, OR a string of the
         see the pyCMS documentation for details on rendering intents and
         what they do.
     direction = integer specifing if the profile is to be used for input,
-        output, or display/proof
+        output, or proof
         INPUT =               0 (or use ImageCms.DIRECTION_INPUT)
         OUTPUT =              1 (or use ImageCms.DIRECTION_OUTPUT)
-        PROOF (or display) =  2 (or use ImageCms.DIRECTION_PROOF)
+        PROOF =               2 (or use ImageCms.DIRECTION_PROOF)
 
     Use this function to verify that you can use your desired
     renderingIntent with profile, and that profile can be used for the
-    input/output/display profile as you desire.
+    input/output/proof profile as you desire.
 
     Some profiles are created specifically for one "direction", can cannot
     be used for others.  Some profiles can only be used for certain
 
     """
     try:
-        if _make_profile(profile).is_intent_supported(intent, direction):
+        if not isinstance(profile, ImageCmsProfile):
+            profile = ImageCmsProfile(profile)
+        # FIXME: I get different results for the same data w. different
+        # compilers.  Bug in LittleCMS or in the binding?
+        if profile.profile.is_intent_supported(intent, direction):
             return 1
         else:
             return -1
         raise PyCMSError(v)
 
 ##
-# Fetches versions.
+# (pyCMS) Fetches versions.
 
 def versions():
     import sys
     pycms, lcms = cmscore.versions()
-    return pycms, "%d.%d" % divmod(lcms, 100), sys.version.split()[0], Image.VERSION
+    return (pycms, "%d.%d" % divmod(lcms, 100),
+            sys.version.split()[0], Image.VERSION)
 
 # --------------------------------------------------------------------
 
 if __name__ == "__main__":
     # create a cheap manual from the __doc__ strings for the functions above
-    
+
     import ImageCms
     import string
     print __doc__
                 print doc
         except AttributeError:
             pass
-   

PIL/ImageDraw2.py

-#
-# The Python Imaging Library
-# $Id: ImageDraw.py 2134 2004-10-06 08:55:20Z fredrik $
-#
-# WCK-style drawing interface operations
-#
-# History:
-# 2003-12-07 fl   created
-# 2005-05-15 fl   updated; added to PIL as ImageDraw2
-# 2005-05-15 fl   added text support
-# 2005-05-20 fl   added arc/chord/pieslice support
-#
-# Copyright (c) 2003-2005 by Secret Labs AB
-# Copyright (c) 2003-2005 by Fredrik Lundh
-#
-# See the README file for information on usage and redistribution.
-#
-
-import Image, ImageColor, ImageDraw, ImageFont, ImagePath
-
-class Pen:
-    def __init__(self, color, width=1, opacity=255):
-        self.color = ImageColor.getrgb(color)
-        self.width = width
-
-class Brush:
-    def __init__(self, color, opacity=255):
-        self.color = ImageColor.getrgb(color)
-
-class Font:
-    def __init__(self, color, file, size=12):
-        # FIXME: add support for bitmap fonts
-        self.color = ImageColor.getrgb(color)
-        self.font = ImageFont.truetype(file, size)
-
-class Draw:
-
-    def __init__(self, image, size=None, color=None):
-        if not hasattr(image, "im"):
-            image = Image.new(image, size, color)
-        self.draw = ImageDraw.Draw(image)
-        self.image = image
-        self.transform = None
-
-    def flush(self):
-        return self.image
-
-    def render(self, op, xy, pen, brush=None):
-        # handle color arguments
-        outline = fill = None; width = 1
-        if isinstance(pen, Pen):
-            outline = pen.color
-            width = pen.width
-        elif isinstance(brush, Pen):
-            outline = brush.color
-            width = brush.width
-        if isinstance(brush, Brush):
-            fill = brush.color
-        elif isinstance(pen, Brush):
-            fill = pen.color
-        # handle transformation
-        if self.transform:
-            xy = ImagePath.Path(xy)
-            xy.transform(self.transform)
-        # render the item
-        if op == "line":
-            self.draw.line(xy, fill=outline, width=width)
-        else:
-            getattr(self.draw, op)(xy, fill=fill, outline=outline)
-
-    def settransform(self, (xoffset, yoffset)):
-        self.transform = (1, 0, xoffset, 0, 1, yoffset)
-
-    def arc(self, xy, start, end, *options):
-        self.render("arc", xy, start, end, *options)
-
-    def chord(self, xy, start, end, *options):
-        self.render("chord", xy, start, end, *options)
-
-    def ellipse(self, xy, *options):
-        self.render("ellipse", xy, *options)
-
-    def line(self, xy, *options):
-        self.render("line", xy, *options)
-
-    def pieslice(self, xy, start, end, *options):
-        self.render("pieslice", xy, start, end, *options)
-
-    def polygon(self, xy, *options):
-        self.render("polygon", xy, *options)
-
-    def rectangle(self, xy, *options):
-        self.render("rectangle", xy, *options)
-
-    def symbol(self, xy, symbol, *options):
-        raise NotImplementedError("not in this version")
-
-    def text(self, xy, text, font):
-        if self.transform:
-            xy = ImagePath.Path(xy)
-            xy.transform(self.transform)
-        self.draw.text(xy, text, font=font.font, fill=font.color)
-
-    def textsize(self, text, font):
-        return self.draw.textsize(text, font=font.font)
+#
+# The Python Imaging Library
+# $Id: ImageDraw.py 2134 2004-10-06 08:55:20Z fredrik $
+#
+# WCK-style drawing interface operations
+#
+# History:
+# 2003-12-07 fl   created
+# 2005-05-15 fl   updated; added to PIL as ImageDraw2
+# 2005-05-15 fl   added text support
+# 2005-05-20 fl   added arc/chord/pieslice support
+#
+# Copyright (c) 2003-2005 by Secret Labs AB
+# Copyright (c) 2003-2005 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+
+import Image, ImageColor, ImageDraw, ImageFont, ImagePath
+
+class Pen:
+    def __init__(self, color, width=1, opacity=255):
+        self.color = ImageColor.getrgb(color)
+        self.width = width
+
+class Brush:
+    def __init__(self, color, opacity=255):
+        self.color = ImageColor.getrgb(color)
+
+class Font:
+    def __init__(self, color, file, size=12):
+        # FIXME: add support for bitmap fonts
+        self.color = ImageColor.getrgb(color)
+        self.font = ImageFont.truetype(file, size)
+
+class Draw:
+
+    def __init__(self, image, size=None, color=None):
+        if not hasattr(image, "im"):
+            image = Image.new(image, size, color)
+        self.draw = ImageDraw.Draw(image)
+        self.image = image
+        self.transform = None
+
+    def flush(self):
+        return self.image
+
+    def render(self, op, xy, pen, brush=None):
+        # handle color arguments
+        outline = fill = None; width = 1
+        if isinstance(pen, Pen):
+            outline = pen.color
+            width = pen.width
+        elif isinstance(brush, Pen):
+            outline = brush.color
+            width = brush.width
+        if isinstance(brush, Brush):
+            fill = brush.color
+        elif isinstance(pen, Brush):
+            fill = pen.color
+        # handle transformation
+        if self.transform:
+            xy = ImagePath.Path(xy)
+            xy.transform(self.transform)
+        # render the item
+        if op == "line":
+            self.draw.line(xy, fill=outline, width=width)
+        else:
+            getattr(self.draw, op)(xy, fill=fill, outline=outline)
+
+    def settransform(self, (xoffset, yoffset)):
+        self.transform = (1, 0, xoffset, 0, 1, yoffset)
+
+    def arc(self, xy, start, end, *options):
+        self.render("arc", xy, start, end, *options)
+
+    def chord(self, xy, start, end, *options):
+        self.render("chord", xy, start, end, *options)
+
+    def ellipse(self, xy, *options):
+        self.render("ellipse", xy, *options)
+
+    def line(self, xy, *options):
+        self.render("line", xy, *options)
+
+    def pieslice(self, xy, start, end, *options):
+        self.render("pieslice", xy, start, end, *options)
+
+    def polygon(self, xy, *options):
+        self.render("polygon", xy, *options)
+
+    def rectangle(self, xy, *options):
+        self.render("rectangle", xy, *options)
+
+    def symbol(self, xy, symbol, *options):
+        raise NotImplementedError("not in this version")
+
+    def text(self, xy, text, font):
+        if self.transform:
+            xy = ImagePath.Path(xy)
+            xy.transform(self.transform)
+        self.draw.text(xy, text, font=font.font, fill=font.color)
+
+    def textsize(self, text, font):
+        return self.draw.textsize(text, font=font.font)
-#
-# The Python Imaging Library.
-# $Id: /work/modules/pil/PIL/ImageFilter.py 486 2004-10-06T08:55:20.930352Z fredrik  $
-#
-# standard mode descriptors
-#
-# History:
-# 2006-03-20 fl   Added
-#
-# Copyright (c) 2006 by Secret Labs AB.
-# Copyright (c) 2006 by Fredrik Lundh.
-#
-# See the README file for information on usage and redistribution.
-#
-
-# mode descriptor cache
-_modes = {}
-
-##
-# Wrapper for mode strings.
-
-class ModeDescriptor:
-
-    def __init__(self, mode, bands, basemode, basetype):
-        self.mode = mode
-        self.bands = bands
-        self.basemode = basemode
-        self.basetype = basetype
-
-    def __str__(self):
-        return self.mode
-
-##
-# Gets a mode descriptor for the given mode.
-
-def getmode(mode):
-    if not _modes:
-        # initialize mode cache
-        import Image
-        # core modes
-        for m, (basemode, basetype, bands) in Image._MODEINFO.items():
-            _modes[m] = ModeDescriptor(m, bands, basemode, basetype)
-        # extra experimental modes
-        _modes["LA"] = ModeDescriptor("LA", ("L", "A"), "L", "L")
-        _modes["PA"] = ModeDescriptor("PA", ("P", "A"), "RGB", "L")
-    return _modes[mode]
+#
+# The Python Imaging Library.
+# $Id: /work/modules/pil/PIL/ImageFilter.py 486 2004-10-06T08:55:20.930352Z fredrik  $
+#
+# standard mode descriptors
+#
+# History:
+# 2006-03-20 fl   Added
+#
+# Copyright (c) 2006 by Secret Labs AB.
+# Copyright (c) 2006 by Fredrik Lundh.
+#
+# See the README file for information on usage and redistribution.
+#
+
+# mode descriptor cache
+_modes = {}
+
+##
+# Wrapper for mode strings.
+
+class ModeDescriptor:
+
+    def __init__(self, mode, bands, basemode, basetype):
+        self.mode = mode
+        self.bands = bands
+        self.basemode = basemode
+        self.basetype = basetype
+
+    def __str__(self):
+        return self.mode
+
+##
+# Gets a mode descriptor for the given mode.
+
+def getmode(mode):
+    if not _modes:
+        # initialize mode cache
+        import Image
+        # core modes
+        for m, (basemode, basetype, bands) in Image._MODEINFO.items():
+            _modes[m] = ModeDescriptor(m, bands, basemode, basetype)
+        # extra experimental modes
+        _modes["LA"] = ModeDescriptor("LA", ("L", "A"), "L", "L")
+        _modes["PA"] = ModeDescriptor("PA", ("P", "A"), "RGB", "L")
+    return _modes[mode]
 
 def unsharp_mask(im, radius=None, percent=None, threshold=None):
     """ PIL_usm.usm(im, [radius, percent, threshold])"""
-    
+
     if radius is None:
         radius = 5.0
     if percent is None:
     return im.im.unsharp_mask(radius, percent, threshold)
 
 usm = unsharp_mask
-

PIL/ImageTransform.py

 
 import Image
 
-class Transform:
+class Transform(Image.ImageTransformHandler):
     def __init__(self, data):
         self.data = data
     def getdata(self):
         return self.method, self.data
+    def transform(self, size, image, **options):
+        # can be overridden
+        method, data = self.getdata()
+        return image.transform(size, method, data, **options)
 
 ##
 # Define an affine image transform.

PIL/McIdasImagePlugin.py

 #
 # History:
 # 1997-05-05 fl  Created (8-bit images only)
-# 2009-03-08 fl  Added 16/32-bit support.  
+# 2009-03-08 fl  Added 16/32-bit support.
 #
 # Thanks to Richard Jones and Craig Swank for specs and samples.
 #

PIL/PngImagePlugin.py

         # ICC profile
         s = ImageFile._safe_read(self.fp, len)
         # according to PNG spec, the iCCP chunk contains:
-        # Profile name 	1-79 bytes (character string)
-        # Null separator 	1 byte (null character)
-        # Compression method 	1 byte (0)
-        # Compressed profile 	n bytes (zlib with deflate compression)
+        # Profile name  1-79 bytes (character string)
+        # Null separator        1 byte (null character)
+        # Compression method    1 byte (0)
+        # Compressed profile    n bytes (zlib with deflate compression)
         i = string.find(s, chr(0))
         if Image.DEBUG:
             print "iCCP profile name", s[:i]
     if im.info.has_key("icc_profile"):
         # ICC profile
         # according to PNG spec, the iCCP chunk contains:
-        # Profile name 	1-79 bytes (character string)
-        # Null separator 	1 byte (null character)
-        # Compression method 	1 byte (0)
-        # Compressed profile 	n bytes (zlib with deflate compression)
+        # Profile name  1-79 bytes (character string)
+        # Null separator        1 byte (null character)
+        # Compression method    1 byte (0)
+        # Compressed profile    n bytes (zlib with deflate compression)
         try:
             import ICCProfile
             p = ICCProfile.ICCProfile(im.info["icc_profile"])

PIL/PsdImagePlugin.py

 
         # skip over blend flags and extra information
         filler = read(12)
-        name = None # FIXME
-        file.seek(i32(read(4)), 1)
+        name = ""
+        size = i32(read(4))
+        combined = 0
+        if size:
+            length = i32(read(4))
+            if length:
+                mask_y = i32(read(4)); mask_x = i32(read(4))
+                mask_h = i32(read(4)) - mask_y; mask_w = i32(read(4)) - mask_x
+                file.seek(length - 16, 1)
+            combined += length + 4
 
+            length = i32(read(4))
+            if length:
+                file.seek(length, 1)
+            combined += length + 4
+
+            length = ord(read(1))
+            if length:
+                name = read(length)
+            combined += length + 1
+
+        file.seek(size - combined, 1)
         layers.append((name, mode, (x0, y0, x1, y1)))
 
     # get tiles

PIL/TiffImagePlugin.py

 
 OPEN_INFO = {
     # (ByteOrder, PhotoInterpretation, SampleFormat, FillOrder, BitsPerSample,
-    #  ExtraSamples) => mode, rawmode 
+    #  ExtraSamples) => mode, rawmode
     (II, 0, 1, 1, (1,), ()): ("1", "1;I"),
     (II, 0, 1, 2, (1,), ()): ("1", "1;IR"),
     (II, 0, 1, 1, (8,), ()): ("L", "L;I"),
     (II, 5, 1, 1, (8,8,8,8), ()): ("CMYK", "CMYK"),
     (II, 6, 1, 1, (8,8,8), ()): ("YCbCr", "YCbCr"),
     (II, 8, 1, 1, (8,8,8), ()): ("LAB", "LAB"),
-   
+
     (MM, 0, 1, 1, (1,), ()): ("1", "1;I"),
     (MM, 0, 1, 2, (1,), ()): ("1", "1;IR"),
     (MM, 0, 1, 1, (8,), ()): ("L", "L;I"),
     (MM, 5, 1, 1, (8,8,8,8), ()): ("CMYK", "CMYK"),
     (MM, 6, 1, 1, (8,8,8), ()): ("YCbCr", "YCbCr"),
     (MM, 8, 1, 1, (8,8,8), ()): ("LAB", "LAB"),
-   
+
 }
 
 PREFIXES = ["MM\000\052", "II\052\000", "II\xBC\000"]
                 print tag, typ, count, repr(value), repr(data)
             fp.write(o16(tag) + o16(typ) + o32(count) + value)
 
-        # -- overwrite here for multi-page -- 
+        # -- overwrite here for multi-page --
         fp.write("\0\0\0\0") # end of directory
 
         # pass 3: write auxiliary data to file
             raise SyntaxError("unknown data organization")
 
         # fixup palette descriptor
-        
+
         if self.mode == "P":
             palette = map(lambda a: chr(a / 256), self.tag[COLORMAP])
             self.palette = ImagePalette.raw("RGB;L", string.join(palette, ""))
     "CMYK": ("CMYK", II, 5, 1, (8,8,8,8), None),
     "YCbCr": ("YCbCr", II, 6, 1, (8,8,8), None),
     "LAB": ("LAB", II, 8, 1, (8,8,8), None),
-   
+
     "I;32BS": ("I;32BS", MM, 1, 2, (32,), None),
     "I;16B": ("I;16B", MM, 1, 1, (16,), None),
     "I;16BS": ("I;16BS", MM, 1, 2, (16,), None),
         ])
 
 
-    # -- helper for multi-page save -- 
+    # -- helper for multi-page save --
     if im.encoderinfo.has_key("_debug_multipage"):
         #just to access o32 and o16 (using correct byte order)
         im._debug_multipage = ifd

PIL/XVThumbImagePlugin.py

         if s != "P7 332":
             raise SyntaxError, "not an XV thumbnail file"
 
+        # Skip to beginning of next line
+        self.fp.readline()
+
         # skip info comments
         while 1:
-            s = string.strip(self.fp.readline())
-            if s == "#END_OF_COMMENTS":
+            s = self.fp.readline()
+            if not s:
+                raise SyntaxError, "Unexpected EOF reading XV thumbnail file"
+            if s[0] != '#':
                 break
 
-        # read header line
-        s = string.split(self.fp.readline())
+        # parse header line (already read)
+        s = string.split(s.strip())
 
         self.mode = "P"
         self.size = int(s[0]), int(s[1])

Tests/crash_ttf_memory_error.py

+from PIL import Image, ImageFont, ImageDraw
+
+font = "../pil-archive/memory-error-2.ttf"
+
+s = "Test Text"
+f = ImageFont.truetype(font, 64, index=0, encoding="unicode")
+w, h = f.getsize(s)
+i = Image.new("RGB", (500, h), "white")
+d = ImageDraw.Draw(i)
+
+# this line causes a MemoryError
+d.text((0,0), s, font=f, fill=0)
+
+i.show()
 
 import glob, os, sys
 
-root = os.path.dirname(__file__)
+try:
+    root = os.path.dirname(__file__)
+except NameError:
+    root = os.path.dirname(sys.argv[0])
+
+if not os.path.isfile("PIL/Image.py"):
+    print "***", "please run this script from the PIL development directory as"
+    print "***", "$ python Tests/run.py"
+    sys.exit(1)
 
 print "-"*68
 

Tests/test_001_archive.py

 
 for file in glob.glob("../pil-archive/*"):
     f, e = os.path.splitext(file)
-    if e in [".txt", ".ttf"]:
+    if e in [".txt", ".ttf", ".otf", ".zip"]:
         continue
     try:
         im = PIL.Image.open(file)

Tests/test_image_convert.py

     for mode in modes:
         im = lena(mode)
         for mode in modes:
-            yield convert, im, mode
+            yield_test(convert, im, mode)

Tests/test_image_copy.py

         assert_equal(out.mode, mode)
         assert_equal(out.size, im.size)
     for mode in "1", "P", "L", "RGB", "I", "F":
-        yield copy, mode
+        yield_test(copy, mode)

Tests/test_image_crop.py

         assert_equal(out.mode, mode)
         assert_equal(out.size, (50, 50))
     for mode in "1", "P", "L", "RGB", "I", "F":
-        yield crop, mode
+        yield_test(crop, mode)
 
 def test_wide_crop():
 

Tests/test_image_resize.py

         assert_equal(out.mode, mode)
         assert_equal(out.size, size)
     for mode in "1", "P", "L", "RGB", "I", "F":
-        yield resize, mode, (100, 100)
-        yield resize, mode, (200, 200)
+        yield_test(resize, mode, (100, 100))
+        yield_test(resize, mode, (200, 200))

Tests/test_image_rotate.py

         assert_equal(out.mode, mode)
         assert_equal(out.size, im.size) # default rotate clips output
     for mode in "1", "P", "L", "RGB", "I", "F":
-        yield rotate, mode
+        yield_test(rotate, mode)

Tests/test_imagechops.py

     assert_equal(table(ImageChops.logical_and, 0, 255), (0, 0, 0, 255))
     assert_equal(table(ImageChops.logical_or, 0, 255), (0, 255, 255, 255))
     assert_equal(table(ImageChops.logical_xor, 0, 255), (0, 255, 255, 0))
-
-
-

Tests/test_imagecms.py

 
     # extensions
     i = Image.open("Tests/images/rgb.jpg")
-    p = ImageCms.getMemoryProfile(i.info["icc_profile"])
+    p = ImageCms.getOpenProfile(StringIO(i.info["icc_profile"]))
     assert_equal(ImageCms.getProfileName(p).strip(),
                  'IEC 61966-2.1 Default RGB colour space - sRGB')
 
     # the procedural pyCMS API uses PyCMSError for all sorts of errors
     assert_exception(ImageCms.PyCMSError, lambda: ImageCms.profileToProfile(lena(), "foo", "bar"))
+    assert_exception(ImageCms.PyCMSError, lambda: ImageCms.buildTransform("foo", "bar", "RGB", "RGB"))
     assert_exception(ImageCms.PyCMSError, lambda: ImageCms.getProfileName(None))
     assert_exception(ImageCms.PyCMSError, lambda: ImageCms.isIntentSupported(SRGB, None, None))
+
+    # test PointTransform convenience API
+    im = lena().point(t)

Tests/test_imagedraw.py

 from PIL import ImageDraw
 
 def test_sanity():
-    
+
     im = lena("RGB").copy()
 
     draw = ImageDraw.ImageDraw(im)

Tests/test_imageenhance.py

 from PIL import ImageEnhance
 
 def test_sanity():
-    
+
     # FIXME: assert_image
     assert_no_exception(lambda: ImageEnhance.Color(lena()).enhance(0.5))
     assert_no_exception(lambda: ImageEnhance.Contrast(lena()).enhance(0.5))

Tests/test_imagepath.py

     assert_equal(list(p), [(0.0, 1.0)])
     p = ImagePath.Path(array.array("f", [0, 1]).tostring())
     assert_equal(list(p), [(0.0, 1.0)])
-
-

Tests/test_numpy.py

 
     assert_image(to_image(numpy.uint8, 3), "RGB", (10, 10))
     assert_image(to_image(numpy.uint8, 4), "RGBA", (10, 10))
-
 _tempfiles = []
 
 def success():
+    import sys
     success.count += 1
+    # print >>open("test.log", "a"), sys.argv[0], success.count, failure.count
 
 def failure(msg=None, frame=None):
     import sys, linecache
         print prefix + line.strip() + " failed:"
     if msg:
         print "- " + msg
+    # print >>open("test.log", "a"), sys.argv[0], success.count, failure.count
 
 success.count = failure.count = 0
 
 # test runner
 
 def run():
-    global _target, run
+    global _target, _tests, run
     import sys, traceback
     _target = sys.modules["__main__"]
     run = None # no need to run twice
     tests.sort() # sort by line
     for lineno, name, func in tests:
         try:
-            result = func()
-            if hasattr(result, "__iter__"):
-                # FIXME: make failure report include the arguments
-                for test in result:
-                    test[0](*test[1:])
+            _tests = []
+            func()
+            for func, args in _tests:
+                func(*args)
         except:
             t, v, tb = sys.exc_info()
             tb = tb.tb_next
                     sys.argv[0], lineno, v)
                 failure.count += 1
 
+def yield_test(function, *args):
+    # collect delayed/generated tests
+    _tests.append((function, args))
+
 def skip(msg=None):
     import os
     print "skip"
  * Copyright (C) 2002-2003 Kevin Cazabon
  * kevin@cazabon.com
  * http://www.cazabon.com
+ * Adapted/reworked for PIL by Fredrik Lundh
+ * Copyright (c) 2009 Fredrik Lundh
  * 
  * pyCMS home page:  http://www.cazabon.com/pyCMS
  * littleCMS home page:  http://www.littlecms.com
 /* version history */
 
 /*
-0.1.0 pil integration
+0.1.0 pil integration & refactoring
 0.0.2 alpha:  Minor updates, added interfaces to littleCMS features, Jan 6, 2003
     - fixed some memory holes in how transforms/profiles were created and passed back to Python
        due to improper destructor setup for PyCObjects
 
 */
 
-/* known to-do list with current version */
+/* known to-do list with current version:
 
-/*
-Add comments to code to make it clearer for others to read/understand!!!
 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 reading and writing embedded profiles in JPEG and TIFF files
 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 other littleCMS features as required
 
 */
 
-
-/* reference */
-
 /*
 INTENT_PERCEPTUAL                 0
 INTENT_RELATIVE_COLORIMETRIC      1
 /* -------------------------------------------------------------------- */
 /* wrapper classes */
 
+/* a profile represents the ICC characteristics for a specific device */
+
 typedef struct {
     PyObject_HEAD
     cmsHPROFILE profile;
     cmsHPROFILE hProfile;
 
     char* sProfile;
-    if (!PyArg_ParseTuple(args, "s:OpenProfile", &sProfile))
+    if (!PyArg_ParseTuple(args, "s:profile_open", &sProfile))
       return NULL;
 
     cmsErrorAction(LCMS_ERROR_IGNORE);
 
     hProfile = cmsOpenProfileFromFile(sProfile, "r");
-    if (!hProfile)
+    if (!hProfile) {
       PyErr_SetString(PyExc_IOError, "cannot open profile file");
+      return NULL;
+    }
 
     return cms_profile_new(hProfile);
 }
 
 static PyObject*
-cms_profile_open_memory(PyObject* self, PyObject* args)
+cms_profile_fromstring(PyObject* self, PyObject* args)
 {
     cmsHPROFILE hProfile;
 
     char* pProfile;
     int nProfile;
-    if (!PyArg_ParseTuple(args, "s#:OpenMemoryProfile", &pProfile, &nProfile))
+    if (!PyArg_ParseTuple(args, "s#:profile_fromstring", &pProfile, &nProfile))
       return NULL;
 
     cmsErrorAction(LCMS_ERROR_IGNORE);
 
     hProfile = cmsOpenProfileFromMem(pProfile, nProfile);
     if (!hProfile)
-      PyErr_SetString(PyExc_IOError, "cannot open memory profile");
+      PyErr_SetString(PyExc_IOError, "cannot open profile from string");
 
     return cms_profile_new(hProfile);
 }
     PyObject_Del(self);
 }
 
+/* a transform represents the mapping between two profiles */
+
 typedef struct {
     PyObject_HEAD
     char mode_in[8];
 }
 
 static cmsHTRANSFORM
-_buildTransform(cmsHPROFILE hInputProfile, cmsHPROFILE hOutputProfile, char *sInMode, char *sOutMode, int iRenderingIntent)
+_buildTransform(cmsHPROFILE hInputProfile, cmsHPROFILE hOutputProfile, char *sInMode, char *sOutMode, int iRenderingIntent, DWORD cmsFLAGS)
 {
   cmsHTRANSFORM hTransform;
 
                                  findLCMStype(sInMode),
                                  hOutputProfile,
                                  findLCMStype(sOutMode),
-                                 iRenderingIntent, 0);
+                                 iRenderingIntent, cmsFLAGS);
 
   Py_END_ALLOW_THREADS
 
 }
 
 static cmsHTRANSFORM
-_buildProofTransform(cmsHPROFILE hInputProfile, cmsHPROFILE hOutputProfile, cmsHPROFILE hDisplayProfile, char *sInMode, char *sOutMode, int iRenderingIntent, int iDisplayIntent)
+_buildProofTransform(cmsHPROFILE hInputProfile, cmsHPROFILE hOutputProfile, cmsHPROFILE hProofProfile, char *sInMode, char *sOutMode, int iRenderingIntent, int iProofIntent, DWORD cmsFLAGS)
 {
   cmsHTRANSFORM hTransform;
 
                           findLCMStype(sInMode),
                           hOutputProfile,
                           findLCMStype(sOutMode),
-                          hDisplayProfile,
+                          hProofProfile,
                           iRenderingIntent,
-                          iDisplayIntent,
-                          0);
+                          iProofIntent,
+                          cmsFLAGS);
 
   Py_END_ALLOW_THREADS
 
   return Py_BuildValue("si", PYCMSVERSION, LCMS_VERSION);
 }
 
-static cmsHPROFILE
-open_profile(const char* sProfile)
-{
-  cmsHPROFILE hProfile;
-
-  hProfile = cmsOpenProfileFromFile(sProfile, "r");
-  if (!hProfile)
-    PyErr_SetString(PyExc_IOError, "cannot open profile file");
-
-  return hProfile;
-}
-
 static PyObject *
 buildTransform(PyObject *self, PyObject *args) {
   CmsProfileObject *pInputProfile;
   char *sInMode;
   char *sOutMode;
   int iRenderingIntent = 0;
+  int cmsFLAGS = 0;
 
   cmsHTRANSFORM transform = NULL;
 
-  if (!PyArg_ParseTuple(args, "O!O!ss|i:buildTransform", &CmsProfile_Type, &pInputProfile, &CmsProfile_Type, &pOutputProfile, &sInMode, &sOutMode, &iRenderingIntent))
+  if (!PyArg_ParseTuple(args, "O!O!ss|ii:buildTransform", &CmsProfile_Type, &pInputProfile, &CmsProfile_Type, &pOutputProfile, &sInMode, &sOutMode, &iRenderingIntent, &cmsFLAGS))
     return NULL;
 
   cmsErrorAction(LCMS_ERROR_IGNORE);
 
-  transform = _buildTransform(pInputProfile->profile, pOutputProfile->profile, sInMode, sOutMode, iRenderingIntent);
+  transform = _buildTransform(pInputProfile->profile, pOutputProfile->profile, sInMode, sOutMode, iRenderingIntent, cmsFLAGS);
 
   if (!transform)
     return NULL;
 {
   CmsProfileObject *pInputProfile;
   CmsProfileObject *pOutputProfile;
-  CmsProfileObject *pDisplayProfile;
+  CmsProfileObject *pProofProfile;
   char *sInMode;
   char *sOutMode;
   int iRenderingIntent = 0;
-  int iDisplayIntent = 0;
+  int iProofIntent = 0;
+  int cmsFLAGS = 0;
 
   cmsHTRANSFORM transform = NULL;
 
-  if (!PyArg_ParseTuple(args, "O!O!O!ss|ii:buildProofTransform", &CmsProfile_Type, &pInputProfile, &CmsProfile_Type, &pOutputProfile, &CmsProfile_Type, &pDisplayProfile, &sInMode, &sOutMode, &iRenderingIntent, &iDisplayIntent))
+  if (!PyArg_ParseTuple(args, "O!O!O!ss|iii:buildProofTransform", &CmsProfile_Type, &pInputProfile, &CmsProfile_Type, &pOutputProfile, &CmsProfile_Type, &pProofProfile, &sInMode, &sOutMode, &iRenderingIntent, &iProofIntent, &cmsFLAGS))
     return NULL;
 
   cmsErrorAction(LCMS_ERROR_IGNORE);
 
-  transform = _buildProofTransform(pInputProfile->profile, pOutputProfile->profile, pDisplayProfile->profile, sInMode, sOutMode, iRenderingIntent, iDisplayIntent);
+  transform = _buildProofTransform(pInputProfile->profile, pOutputProfile->profile, pProofProfile->profile, sInMode, sOutMode, iRenderingIntent, iProofIntent, cmsFLAGS);
   
   if (!transform)
     return NULL;
 }
 
 static PyObject *
-applyTransform(PyObject *self, PyObject *args)
+cms_transform_apply(CmsTransformObject *self, PyObject *args)
 {
   long idIn;
   long idOut;
-  CmsTransformObject *pTransform;
-  cmsHTRANSFORM hTransform;
   Imaging im;
   Imaging imOut;
 
   int result;
 
-  if (!PyArg_ParseTuple(args, "llO!:applyTransform", &idIn, &idOut, &CmsTransform_Type, &pTransform))
+  if (!PyArg_ParseTuple(args, "ll:apply", &idIn, &idOut))
     return NULL;
 
   im = (Imaging) idIn;
   imOut = (Imaging) idOut;
 
-  cmsErrorAction(LCMS_ERROR_SHOW); /* FIXME */
-
-  hTransform = pTransform->transform; 
-
-  result = pyCMSdoTransform(im, imOut, hTransform);
-
-  return Py_BuildValue("i", result);
-}
-
-static PyObject *
-profileToProfile(PyObject *self, PyObject *args)
-{
-  Imaging im;
-  Imaging imOut;
-  long idIn;
-  long idOut = 0L;
-  char *sInputProfile = NULL;
-  char *sOutputProfile = NULL;
-  int iRenderingIntent = 0;
-  char *inMode;
-  char *outMode;
-  int result;
-
-  cmsHTRANSFORM hTransform = NULL;
-  cmsHPROFILE hInputProfile = NULL;
-  cmsHPROFILE hOutputProfile = NULL;
-
-  /* parse the PyObject arguments, assign to variables accordingly */
-  if (!PyArg_ParseTuple(args, "llss|i:profileToProfile", &idIn, &idOut, &sInputProfile, &sOutputProfile, &iRenderingIntent))
-    return NULL;
-
-  im = (Imaging) idIn;
-
-  if (idOut != 0L) {
-    imOut = (Imaging) idOut;
-  } else
-    imOut = NULL;
-
   cmsErrorAction(LCMS_ERROR_IGNORE);
 
-  /* Check the modes of imIn and imOut to set the color type for the
-     transform.  Note that the modes do NOT have to be the same, as
-     long as they are each supported by the relevant profile
-     specified */
+  result = pyCMSdoTransform(im, imOut, self->transform);
 
-  inMode = im->mode;
-  if (idOut == 0L) {
-    outMode = inMode;
-  } else {
-    outMode = imOut->mode;
-  }
-
-  hInputProfile  = open_profile(sInputProfile);
-  hOutputProfile = open_profile(sOutputProfile);
-
-  if (hInputProfile && hOutputProfile)
-    hTransform = _buildTransform(hInputProfile, hOutputProfile, inMode, outMode, iRenderingIntent);
-
-  if (hOutputProfile)
-    cmsCloseProfile(hOutputProfile);
-  if (hInputProfile)
-    cmsCloseProfile(hInputProfile);
-
-  if (!hTransform)
-    return NULL;
-
-  /* apply the transform to imOut (or directly to im in place if idOut
-     is not supplied) */
-  if (idOut != 0L) {
-    result = pyCMSdoTransform(im, imOut, hTransform);
-  } else {
-    result = pyCMSdoTransform(im, im, hTransform);
-  }
-
-  cmsDeleteTransform(hTransform);
-
-  /* return 0 on success, -1 on failure */
   return Py_BuildValue("i", result);
 }
 
   if (!PyArg_ParseTuple(args, "s|i:createProfile", &sColorSpace, &iColorTemp))
     return NULL;
 
-  cmsErrorAction(LCMS_ERROR_SHOW); /* FIXME */
+  cmsErrorAction(LCMS_ERROR_IGNORE);
 
   if (strcmp(sColorSpace, "LAB") == 0) {
     if (iColorTemp > 0) {
 	return NULL;
       }
       hProfile = cmsCreateLabProfile(whitePoint);
-    }
-    else {
+    } else
       hProfile = cmsCreateLabProfile(NULL);
-    }
   }
-  else if (strcmp(sColorSpace, "XYZ") == 0) {
+  else if (strcmp(sColorSpace, "XYZ") == 0)
     hProfile = cmsCreateXYZProfile();
-  }
-  else if (strcmp(sColorSpace, "sRGB") == 0) {
+  else if (strcmp(sColorSpace, "sRGB") == 0)
     hProfile = cmsCreate_sRGBProfile();
-  }
-  else {
-    PyErr_SetString(PyExc_ValueError, "ERROR: Color space requested is not valid for built-in profiles");
+  else
+    hProfile = NULL;
+
+  if (!hProfile) {
+    PyErr_SetString(PyExc_ValueError, "failed to create requested color space");
     return NULL;
   }
 
 static PyMethodDef pyCMSdll_methods[] = {
 
   {"profile_open", cms_profile_open, 1},
-  {"profile_fromstring", cms_profile_open_memory, 1},
+  {"profile_fromstring", cms_profile_fromstring, 1},
 
   /* pyCMS info */
   {"versions", versions, 1},
 
   /* profile and transform functions */
-  {"profileToProfile", profileToProfile, 1},
   {"buildTransform", buildTransform, 1},
   {"buildProofTransform", buildProofTransform, 1},
-  {"applyTransform", applyTransform, 1},
   {"createProfile", createProfile, 1},
 
   {NULL, NULL}
     return PyString_FromString(cmsTakeProductDesc(self->profile));
   if (!strcmp(name, "product_info"))
     return PyString_FromString(cmsTakeProductInfo(self->profile));
-  if (!strcmp(name, "manufacturer"))
-    return PyString_FromString(cmsTakeManufacturer(self->profile));
-  if (!strcmp(name, "model"))
-    return PyString_FromString(cmsTakeModel(self->profile));
-  if (!strcmp(name, "copyright"))
-    return PyString_FromString(cmsTakeCopyright(self->profile));
   if (!strcmp(name, "rendering_intent"))
     return PyInt_FromLong(cmsTakeRenderingIntent(self->profile));
   if (!strcmp(name, "pcs"))
 };
 
 static struct PyMethodDef cms_transform_methods[] = {
+    {"apply", (PyCFunction) cms_transform_apply, 1},
     {NULL, NULL} /* sentinel */
 };
 
 #define MOD_I(type, v1, v2) ((v2)!=0)?(v1)%(v2):0
 #define MOD_F(type, v1, v2) ((v2)!=0.0F)?fmod((v1),(v2)):0.0F
 
+#define POW_F(type, v1, v2) powf(v1, v2) /* EDOM handling */
+
 #define DIFF_I(type, v1, v2) abs((v1)-(v2))
 #define DIFF_F(type, v1, v2) fabs((v1)-(v2))
 
 BINOP(mul_F, MUL, FLOAT32)
 BINOP(div_F, DIV_F, FLOAT32)
 BINOP(mod_F, MOD_F, FLOAT32)
+BINOP(pow_F, POW_F, FLOAT32)
 BINOP(diff_F, DIFF_F, FLOAT32)
 
 BINOP(min_F, MIN, FLOAT32)
     install(d, "mod_F", mod_F);
     install(d, "min_F", min_F);
     install(d, "max_F", max_F);
+    install(d, "pow_F", pow_F);
 
     install(d, "eq_F", eq_F);
     install(d, "ne_F", ne_F);
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.