ImageCms.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. # The Python Imaging Library.
  2. # $Id$
  3. # Optional color management support, based on Kevin Cazabon's PyCMS
  4. # library.
  5. # History:
  6. # 2009-03-08 fl Added to PIL.
  7. # Copyright (C) 2002-2003 Kevin Cazabon
  8. # Copyright (c) 2009 by Fredrik Lundh
  9. # Copyright (c) 2013 by Eric Soroos
  10. # See the README file for information on usage and redistribution. See
  11. # below for the original description.
  12. from __future__ import annotations
  13. import sys
  14. from enum import IntEnum
  15. from . import Image
  16. try:
  17. from . import _imagingcms
  18. except ImportError as ex:
  19. # Allow error import for doc purposes, but error out when accessing
  20. # anything in core.
  21. from ._util import DeferredError
  22. _imagingcms = DeferredError.new(ex)
  23. DESCRIPTION = """
  24. pyCMS
  25. a Python / PIL interface to the littleCMS ICC Color Management System
  26. Copyright (C) 2002-2003 Kevin Cazabon
  27. kevin@cazabon.com
  28. https://www.cazabon.com
  29. pyCMS home page: https://www.cazabon.com/pyCMS
  30. littleCMS home page: https://www.littlecms.com
  31. (littleCMS is Copyright (C) 1998-2001 Marti Maria)
  32. Originally released under LGPL. Graciously donated to PIL in
  33. March 2009, for distribution under the standard PIL license
  34. The pyCMS.py module provides a "clean" interface between Python/PIL and
  35. pyCMSdll, taking care of some of the more complex handling of the direct
  36. pyCMSdll functions, as well as error-checking and making sure that all
  37. relevant data is kept together.
  38. While it is possible to call pyCMSdll functions directly, it's not highly
  39. recommended.
  40. Version History:
  41. 1.0.0 pil Oct 2013 Port to LCMS 2.
  42. 0.1.0 pil mod March 10, 2009
  43. Renamed display profile to proof profile. The proof
  44. profile is the profile of the device that is being
  45. simulated, not the profile of the device which is
  46. actually used to display/print the final simulation
  47. (that'd be the output profile) - also see LCMSAPI.txt
  48. input colorspace -> using 'renderingIntent' -> proof
  49. colorspace -> using 'proofRenderingIntent' -> output
  50. colorspace
  51. Added LCMS FLAGS support.
  52. Added FLAGS["SOFTPROOFING"] as default flag for
  53. buildProofTransform (otherwise the proof profile/intent
  54. would be ignored).
  55. 0.1.0 pil March 2009 - added to PIL, as PIL.ImageCms
  56. 0.0.2 alpha Jan 6, 2002
  57. Added try/except statements around type() checks of
  58. potential CObjects... Python won't let you use type()
  59. on them, and raises a TypeError (stupid, if you ask
  60. me!)
  61. Added buildProofTransformFromOpenProfiles() function.
  62. Additional fixes in DLL, see DLL code for details.
  63. 0.0.1 alpha first public release, Dec. 26, 2002
  64. Known to-do list with current version (of Python interface, not pyCMSdll):
  65. none
  66. """
  67. VERSION = "1.0.0 pil"
  68. # --------------------------------------------------------------------.
  69. core = _imagingcms
  70. #
  71. # intent/direction values
  72. class Intent(IntEnum):
  73. PERCEPTUAL = 0
  74. RELATIVE_COLORIMETRIC = 1
  75. SATURATION = 2
  76. ABSOLUTE_COLORIMETRIC = 3
  77. class Direction(IntEnum):
  78. INPUT = 0
  79. OUTPUT = 1
  80. PROOF = 2
  81. #
  82. # flags
  83. FLAGS = {
  84. "MATRIXINPUT": 1,
  85. "MATRIXOUTPUT": 2,
  86. "MATRIXONLY": (1 | 2),
  87. "NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot
  88. # Don't create prelinearization tables on precalculated transforms
  89. # (internal use):
  90. "NOPRELINEARIZATION": 16,
  91. "GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink)
  92. "NOTCACHE": 64, # Inhibit 1-pixel cache
  93. "NOTPRECALC": 256,
  94. "NULLTRANSFORM": 512, # Don't transform anyway
  95. "HIGHRESPRECALC": 1024, # Use more memory to give better accuracy
  96. "LOWRESPRECALC": 2048, # Use less memory to minimize resources
  97. "WHITEBLACKCOMPENSATION": 8192,
  98. "BLACKPOINTCOMPENSATION": 8192,
  99. "GAMUTCHECK": 4096, # Out of Gamut alarm
  100. "SOFTPROOFING": 16384, # Do softproofing
  101. "PRESERVEBLACK": 32768, # Black preservation
  102. "NODEFAULTRESOURCEDEF": 16777216, # CRD special
  103. "GRIDPOINTS": lambda n: (n & 0xFF) << 16, # Gridpoints
  104. }
  105. _MAX_FLAG = 0
  106. for flag in FLAGS.values():
  107. if isinstance(flag, int):
  108. _MAX_FLAG = _MAX_FLAG | flag
  109. # --------------------------------------------------------------------.
  110. # Experimental PIL-level API
  111. # --------------------------------------------------------------------.
  112. ##
  113. # Profile.
  114. class ImageCmsProfile:
  115. def __init__(self, profile):
  116. """
  117. :param profile: Either a string representing a filename,
  118. a file like object containing a profile or a
  119. low-level profile object
  120. """
  121. if isinstance(profile, str):
  122. if sys.platform == "win32":
  123. profile_bytes_path = profile.encode()
  124. try:
  125. profile_bytes_path.decode("ascii")
  126. except UnicodeDecodeError:
  127. with open(profile, "rb") as f:
  128. self._set(core.profile_frombytes(f.read()))
  129. return
  130. self._set(core.profile_open(profile), profile)
  131. elif hasattr(profile, "read"):
  132. self._set(core.profile_frombytes(profile.read()))
  133. elif isinstance(profile, _imagingcms.CmsProfile):
  134. self._set(profile)
  135. else:
  136. msg = "Invalid type for Profile"
  137. raise TypeError(msg)
  138. def _set(self, profile, filename=None):
  139. self.profile = profile
  140. self.filename = filename
  141. self.product_name = None # profile.product_name
  142. self.product_info = None # profile.product_info
  143. def tobytes(self):
  144. """
  145. Returns the profile in a format suitable for embedding in
  146. saved images.
  147. :returns: a bytes object containing the ICC profile.
  148. """
  149. return core.profile_tobytes(self.profile)
  150. class ImageCmsTransform(Image.ImagePointHandler):
  151. """
  152. Transform. This can be used with the procedural API, or with the standard
  153. :py:func:`~PIL.Image.Image.point` method.
  154. Will return the output profile in the ``output.info['icc_profile']``.
  155. """
  156. def __init__(
  157. self,
  158. input,
  159. output,
  160. input_mode,
  161. output_mode,
  162. intent=Intent.PERCEPTUAL,
  163. proof=None,
  164. proof_intent=Intent.ABSOLUTE_COLORIMETRIC,
  165. flags=0,
  166. ):
  167. if proof is None:
  168. self.transform = core.buildTransform(
  169. input.profile, output.profile, input_mode, output_mode, intent, flags
  170. )
  171. else:
  172. self.transform = core.buildProofTransform(
  173. input.profile,
  174. output.profile,
  175. proof.profile,
  176. input_mode,
  177. output_mode,
  178. intent,
  179. proof_intent,
  180. flags,
  181. )
  182. # Note: inputMode and outputMode are for pyCMS compatibility only
  183. self.input_mode = self.inputMode = input_mode
  184. self.output_mode = self.outputMode = output_mode
  185. self.output_profile = output
  186. def point(self, im):
  187. return self.apply(im)
  188. def apply(self, im, imOut=None):
  189. im.load()
  190. if imOut is None:
  191. imOut = Image.new(self.output_mode, im.size, None)
  192. self.transform.apply(im.im.id, imOut.im.id)
  193. imOut.info["icc_profile"] = self.output_profile.tobytes()
  194. return imOut
  195. def apply_in_place(self, im):
  196. im.load()
  197. if im.mode != self.output_mode:
  198. msg = "mode mismatch"
  199. raise ValueError(msg) # wrong output mode
  200. self.transform.apply(im.im.id, im.im.id)
  201. im.info["icc_profile"] = self.output_profile.tobytes()
  202. return im
  203. def get_display_profile(handle=None):
  204. """
  205. (experimental) Fetches the profile for the current display device.
  206. :returns: ``None`` if the profile is not known.
  207. """
  208. if sys.platform != "win32":
  209. return None
  210. from . import ImageWin
  211. if isinstance(handle, ImageWin.HDC):
  212. profile = core.get_display_profile_win32(handle, 1)
  213. else:
  214. profile = core.get_display_profile_win32(handle or 0)
  215. if profile is None:
  216. return None
  217. return ImageCmsProfile(profile)
  218. # --------------------------------------------------------------------.
  219. # pyCMS compatible layer
  220. # --------------------------------------------------------------------.
  221. class PyCMSError(Exception):
  222. """(pyCMS) Exception class.
  223. This is used for all errors in the pyCMS API."""
  224. pass
  225. def profileToProfile(
  226. im,
  227. inputProfile,
  228. outputProfile,
  229. renderingIntent=Intent.PERCEPTUAL,
  230. outputMode=None,
  231. inPlace=False,
  232. flags=0,
  233. ):
  234. """
  235. (pyCMS) Applies an ICC transformation to a given image, mapping from
  236. ``inputProfile`` to ``outputProfile``.
  237. If the input or output profiles specified are not valid filenames, a
  238. :exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
  239. ``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
  240. If an error occurs during application of the profiles,
  241. a :exc:`PyCMSError` will be raised.
  242. If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
  243. a :exc:`PyCMSError` will be raised.
  244. This function applies an ICC transformation to im from ``inputProfile``'s
  245. color space to ``outputProfile``'s color space using the specified rendering
  246. intent to decide how to handle out-of-gamut colors.
  247. ``outputMode`` can be used to specify that a color mode conversion is to
  248. be done using these profiles, but the specified profiles must be able
  249. to handle that mode. I.e., if converting im from RGB to CMYK using
  250. profiles, the input profile must handle RGB data, and the output
  251. profile must handle CMYK data.
  252. :param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
  253. or Image.open(...), etc.)
  254. :param inputProfile: String, as a valid filename path to the ICC input
  255. profile you wish to use for this image, or a profile object
  256. :param outputProfile: String, as a valid filename path to the ICC output
  257. profile you wish to use for this image, or a profile object
  258. :param renderingIntent: Integer (0-3) specifying the rendering intent you
  259. wish to use for the transform
  260. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  261. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  262. ImageCms.Intent.SATURATION = 2
  263. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  264. see the pyCMS documentation for details on rendering intents and what
  265. they do.
  266. :param outputMode: A valid PIL mode for the output image (i.e. "RGB",
  267. "CMYK", etc.). Note: if rendering the image "inPlace", outputMode
  268. MUST be the same mode as the input, or omitted completely. If
  269. omitted, the outputMode will be the same as the mode of the input
  270. image (im.mode)
  271. :param inPlace: Boolean. If ``True``, the original image is modified in-place,
  272. and ``None`` is returned. If ``False`` (default), a new
  273. :py:class:`~PIL.Image.Image` object is returned with the transform applied.
  274. :param flags: Integer (0-...) specifying additional flags
  275. :returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
  276. the value of ``inPlace``
  277. :exception PyCMSError:
  278. """
  279. if outputMode is None:
  280. outputMode = im.mode
  281. if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
  282. msg = "renderingIntent must be an integer between 0 and 3"
  283. raise PyCMSError(msg)
  284. if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
  285. msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
  286. raise PyCMSError(msg)
  287. try:
  288. if not isinstance(inputProfile, ImageCmsProfile):
  289. inputProfile = ImageCmsProfile(inputProfile)
  290. if not isinstance(outputProfile, ImageCmsProfile):
  291. outputProfile = ImageCmsProfile(outputProfile)
  292. transform = ImageCmsTransform(
  293. inputProfile,
  294. outputProfile,
  295. im.mode,
  296. outputMode,
  297. renderingIntent,
  298. flags=flags,
  299. )
  300. if inPlace:
  301. transform.apply_in_place(im)
  302. imOut = None
  303. else:
  304. imOut = transform.apply(im)
  305. except (OSError, TypeError, ValueError) as v:
  306. raise PyCMSError(v) from v
  307. return imOut
  308. def getOpenProfile(profileFilename):
  309. """
  310. (pyCMS) Opens an ICC profile file.
  311. The PyCMSProfile object can be passed back into pyCMS for use in creating
  312. transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
  313. If ``profileFilename`` is not a valid filename for an ICC profile,
  314. a :exc:`PyCMSError` will be raised.
  315. :param profileFilename: String, as a valid filename path to the ICC profile
  316. you wish to open, or a file-like object.
  317. :returns: A CmsProfile class object.
  318. :exception PyCMSError:
  319. """
  320. try:
  321. return ImageCmsProfile(profileFilename)
  322. except (OSError, TypeError, ValueError) as v:
  323. raise PyCMSError(v) from v
  324. def buildTransform(
  325. inputProfile,
  326. outputProfile,
  327. inMode,
  328. outMode,
  329. renderingIntent=Intent.PERCEPTUAL,
  330. flags=0,
  331. ):
  332. """
  333. (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
  334. ``outputProfile``. Use applyTransform to apply the transform to a given
  335. image.
  336. If the input or output profiles specified are not valid filenames, a
  337. :exc:`PyCMSError` will be raised. If an error occurs during creation
  338. of the transform, a :exc:`PyCMSError` will be raised.
  339. If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
  340. (or by pyCMS), a :exc:`PyCMSError` will be raised.
  341. This function builds and returns an ICC transform from the ``inputProfile``
  342. to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
  343. with out-of-gamut colors. It will ONLY work for converting images that
  344. are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
  345. i.e. "RGB", "RGBA", "CMYK", etc.).
  346. Building the transform is a fair part of the overhead in
  347. ImageCms.profileToProfile(), so if you're planning on converting multiple
  348. images using the same input/output settings, this can save you time.
  349. Once you have a transform object, it can be used with
  350. ImageCms.applyProfile() to convert images without the need to re-compute
  351. the lookup table for the transform.
  352. The reason pyCMS returns a class object rather than a handle directly
  353. to the transform is that it needs to keep track of the PIL input/output
  354. modes that the transform is meant for. These attributes are stored in
  355. the ``inMode`` and ``outMode`` attributes of the object (which can be
  356. manually overridden if you really want to, but I don't know of any
  357. time that would be of use, or would even work).
  358. :param inputProfile: String, as a valid filename path to the ICC input
  359. profile you wish to use for this transform, or a profile object
  360. :param outputProfile: String, as a valid filename path to the ICC output
  361. profile you wish to use for this transform, or a profile object
  362. :param inMode: String, as a valid PIL mode that the appropriate profile
  363. also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
  364. :param outMode: String, as a valid PIL mode that the appropriate profile
  365. also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
  366. :param renderingIntent: Integer (0-3) specifying the rendering intent you
  367. wish to use for the transform
  368. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  369. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  370. ImageCms.Intent.SATURATION = 2
  371. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  372. see the pyCMS documentation for details on rendering intents and what
  373. they do.
  374. :param flags: Integer (0-...) specifying additional flags
  375. :returns: A CmsTransform class object.
  376. :exception PyCMSError:
  377. """
  378. if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
  379. msg = "renderingIntent must be an integer between 0 and 3"
  380. raise PyCMSError(msg)
  381. if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
  382. msg = "flags must be an integer between 0 and %s" + _MAX_FLAG
  383. raise PyCMSError(msg)
  384. try:
  385. if not isinstance(inputProfile, ImageCmsProfile):
  386. inputProfile = ImageCmsProfile(inputProfile)
  387. if not isinstance(outputProfile, ImageCmsProfile):
  388. outputProfile = ImageCmsProfile(outputProfile)
  389. return ImageCmsTransform(
  390. inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
  391. )
  392. except (OSError, TypeError, ValueError) as v:
  393. raise PyCMSError(v) from v
  394. def buildProofTransform(
  395. inputProfile,
  396. outputProfile,
  397. proofProfile,
  398. inMode,
  399. outMode,
  400. renderingIntent=Intent.PERCEPTUAL,
  401. proofRenderingIntent=Intent.ABSOLUTE_COLORIMETRIC,
  402. flags=FLAGS["SOFTPROOFING"],
  403. ):
  404. """
  405. (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
  406. ``outputProfile``, but tries to simulate the result that would be
  407. obtained on the ``proofProfile`` device.
  408. If the input, output, or proof profiles specified are not valid
  409. filenames, a :exc:`PyCMSError` will be raised.
  410. If an error occurs during creation of the transform,
  411. a :exc:`PyCMSError` will be raised.
  412. If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
  413. (or by pyCMS), a :exc:`PyCMSError` will be raised.
  414. This function builds and returns an ICC transform from the ``inputProfile``
  415. to the ``outputProfile``, but tries to simulate the result that would be
  416. obtained on the ``proofProfile`` device using ``renderingIntent`` and
  417. ``proofRenderingIntent`` to determine what to do with out-of-gamut
  418. colors. This is known as "soft-proofing". It will ONLY work for
  419. converting images that are in ``inMode`` to images that are in outMode
  420. color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
  421. Usage of the resulting transform object is exactly the same as with
  422. ImageCms.buildTransform().
  423. Proof profiling is generally used when using an output device to get a
  424. good idea of what the final printed/displayed image would look like on
  425. the ``proofProfile`` device when it's quicker and easier to use the
  426. output device for judging color. Generally, this means that the
  427. output device is a monitor, or a dye-sub printer (etc.), and the simulated
  428. device is something more expensive, complicated, or time consuming
  429. (making it difficult to make a real print for color judgement purposes).
  430. Soft-proofing basically functions by adjusting the colors on the
  431. output device to match the colors of the device being simulated. However,
  432. when the simulated device has a much wider gamut than the output
  433. device, you may obtain marginal results.
  434. :param inputProfile: String, as a valid filename path to the ICC input
  435. profile you wish to use for this transform, or a profile object
  436. :param outputProfile: String, as a valid filename path to the ICC output
  437. (monitor, usually) profile you wish to use for this transform, or a
  438. profile object
  439. :param proofProfile: String, as a valid filename path to the ICC proof
  440. profile you wish to use for this transform, or a profile object
  441. :param inMode: String, as a valid PIL mode that the appropriate profile
  442. also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
  443. :param outMode: String, as a valid PIL mode that the appropriate profile
  444. also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
  445. :param renderingIntent: Integer (0-3) specifying the rendering intent you
  446. wish to use for the input->proof (simulated) transform
  447. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  448. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  449. ImageCms.Intent.SATURATION = 2
  450. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  451. see the pyCMS documentation for details on rendering intents and what
  452. they do.
  453. :param proofRenderingIntent: Integer (0-3) specifying the rendering intent
  454. you wish to use for proof->output transform
  455. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  456. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  457. ImageCms.Intent.SATURATION = 2
  458. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  459. see the pyCMS documentation for details on rendering intents and what
  460. they do.
  461. :param flags: Integer (0-...) specifying additional flags
  462. :returns: A CmsTransform class object.
  463. :exception PyCMSError:
  464. """
  465. if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
  466. msg = "renderingIntent must be an integer between 0 and 3"
  467. raise PyCMSError(msg)
  468. if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
  469. msg = "flags must be an integer between 0 and %s" + _MAX_FLAG
  470. raise PyCMSError(msg)
  471. try:
  472. if not isinstance(inputProfile, ImageCmsProfile):
  473. inputProfile = ImageCmsProfile(inputProfile)
  474. if not isinstance(outputProfile, ImageCmsProfile):
  475. outputProfile = ImageCmsProfile(outputProfile)
  476. if not isinstance(proofProfile, ImageCmsProfile):
  477. proofProfile = ImageCmsProfile(proofProfile)
  478. return ImageCmsTransform(
  479. inputProfile,
  480. outputProfile,
  481. inMode,
  482. outMode,
  483. renderingIntent,
  484. proofProfile,
  485. proofRenderingIntent,
  486. flags,
  487. )
  488. except (OSError, TypeError, ValueError) as v:
  489. raise PyCMSError(v) from v
  490. buildTransformFromOpenProfiles = buildTransform
  491. buildProofTransformFromOpenProfiles = buildProofTransform
  492. def applyTransform(im, transform, inPlace=False):
  493. """
  494. (pyCMS) Applies a transform to a given image.
  495. If ``im.mode != transform.inMode``, a :exc:`PyCMSError` is raised.
  496. If ``inPlace`` is ``True`` and ``transform.inMode != transform.outMode``, a
  497. :exc:`PyCMSError` is raised.
  498. If ``im.mode``, ``transform.inMode`` or ``transform.outMode`` is not
  499. supported by pyCMSdll or the profiles you used for the transform, a
  500. :exc:`PyCMSError` is raised.
  501. If an error occurs while the transform is being applied,
  502. a :exc:`PyCMSError` is raised.
  503. This function applies a pre-calculated transform (from
  504. ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
  505. to an image. The transform can be used for multiple images, saving
  506. considerable calculation time if doing the same conversion multiple times.
  507. If you want to modify im in-place instead of receiving a new image as
  508. the return value, set ``inPlace`` to ``True``. This can only be done if
  509. ``transform.inMode`` and ``transform.outMode`` are the same, because we can't
  510. change the mode in-place (the buffer sizes for some modes are
  511. different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
  512. object of the same dimensions in mode ``transform.outMode``.
  513. :param im: An :py:class:`~PIL.Image.Image` object, and im.mode must be the same
  514. as the ``inMode`` supported by the transform.
  515. :param transform: A valid CmsTransform class object
  516. :param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
  517. returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
  518. transform applied is returned (and ``im`` is not changed). The default is
  519. ``False``.
  520. :returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
  521. depending on the value of ``inPlace``. The profile will be returned in
  522. the image's ``info['icc_profile']``.
  523. :exception PyCMSError:
  524. """
  525. try:
  526. if inPlace:
  527. transform.apply_in_place(im)
  528. imOut = None
  529. else:
  530. imOut = transform.apply(im)
  531. except (TypeError, ValueError) as v:
  532. raise PyCMSError(v) from v
  533. return imOut
  534. def createProfile(colorSpace, colorTemp=-1):
  535. """
  536. (pyCMS) Creates a profile.
  537. If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
  538. a :exc:`PyCMSError` is raised.
  539. If using LAB and ``colorTemp`` is not a positive integer,
  540. a :exc:`PyCMSError` is raised.
  541. If an error occurs while creating the profile,
  542. a :exc:`PyCMSError` is raised.
  543. Use this function to create common profiles on-the-fly instead of
  544. having to supply a profile on disk and knowing the path to it. It
  545. returns a normal CmsProfile object that can be passed to
  546. ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
  547. to images.
  548. :param colorSpace: String, the color space of the profile you wish to
  549. create.
  550. Currently only "LAB", "XYZ", and "sRGB" are supported.
  551. :param colorTemp: Positive integer for the white point for the profile, in
  552. degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
  553. illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
  554. profiles, and is ignored for XYZ and sRGB.
  555. :returns: A CmsProfile class object
  556. :exception PyCMSError:
  557. """
  558. if colorSpace not in ["LAB", "XYZ", "sRGB"]:
  559. msg = (
  560. f"Color space not supported for on-the-fly profile creation ({colorSpace})"
  561. )
  562. raise PyCMSError(msg)
  563. if colorSpace == "LAB":
  564. try:
  565. colorTemp = float(colorTemp)
  566. except (TypeError, ValueError) as e:
  567. msg = f'Color temperature must be numeric, "{colorTemp}" not valid'
  568. raise PyCMSError(msg) from e
  569. try:
  570. return core.createProfile(colorSpace, colorTemp)
  571. except (TypeError, ValueError) as v:
  572. raise PyCMSError(v) from v
  573. def getProfileName(profile):
  574. """
  575. (pyCMS) Gets the internal product name for the given profile.
  576. If ``profile`` isn't a valid CmsProfile object or filename to a profile,
  577. a :exc:`PyCMSError` is raised If an error occurs while trying
  578. to obtain the name tag, a :exc:`PyCMSError` is raised.
  579. Use this function to obtain the INTERNAL name of the profile (stored
  580. in an ICC tag in the profile itself), usually the one used when the
  581. profile was originally created. Sometimes this tag also contains
  582. additional information supplied by the creator.
  583. :param profile: EITHER a valid CmsProfile object, OR a string of the
  584. filename of an ICC profile.
  585. :returns: A string containing the internal name of the profile as stored
  586. in an ICC tag.
  587. :exception PyCMSError:
  588. """
  589. try:
  590. # add an extra newline to preserve pyCMS compatibility
  591. if not isinstance(profile, ImageCmsProfile):
  592. profile = ImageCmsProfile(profile)
  593. # do it in python, not c.
  594. # // name was "%s - %s" (model, manufacturer) || Description ,
  595. # // but if the Model and Manufacturer were the same or the model
  596. # // was long, Just the model, in 1.x
  597. model = profile.profile.model
  598. manufacturer = profile.profile.manufacturer
  599. if not (model or manufacturer):
  600. return (profile.profile.profile_description or "") + "\n"
  601. if not manufacturer or len(model) > 30:
  602. return model + "\n"
  603. return f"{model} - {manufacturer}\n"
  604. except (AttributeError, OSError, TypeError, ValueError) as v:
  605. raise PyCMSError(v) from v
  606. def getProfileInfo(profile):
  607. """
  608. (pyCMS) Gets the internal product information for the given profile.
  609. If ``profile`` isn't a valid CmsProfile object or filename to a profile,
  610. a :exc:`PyCMSError` is raised.
  611. If an error occurs while trying to obtain the info tag,
  612. a :exc:`PyCMSError` is raised.
  613. Use this function to obtain the information stored in the profile's
  614. info tag. This often contains details about the profile, and how it
  615. was created, as supplied by the creator.
  616. :param profile: EITHER a valid CmsProfile object, OR a string of the
  617. filename of an ICC profile.
  618. :returns: A string containing the internal profile information stored in
  619. an ICC tag.
  620. :exception PyCMSError:
  621. """
  622. try:
  623. if not isinstance(profile, ImageCmsProfile):
  624. profile = ImageCmsProfile(profile)
  625. # add an extra newline to preserve pyCMS compatibility
  626. # Python, not C. the white point bits weren't working well,
  627. # so skipping.
  628. # info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint
  629. description = profile.profile.profile_description
  630. cpright = profile.profile.copyright
  631. elements = [element for element in (description, cpright) if element]
  632. return "\r\n\r\n".join(elements) + "\r\n\r\n"
  633. except (AttributeError, OSError, TypeError, ValueError) as v:
  634. raise PyCMSError(v) from v
  635. def getProfileCopyright(profile):
  636. """
  637. (pyCMS) Gets the copyright for the given profile.
  638. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
  639. :exc:`PyCMSError` is raised.
  640. If an error occurs while trying to obtain the copyright tag,
  641. a :exc:`PyCMSError` is raised.
  642. Use this function to obtain the information stored in the profile's
  643. copyright tag.
  644. :param profile: EITHER a valid CmsProfile object, OR a string of the
  645. filename of an ICC profile.
  646. :returns: A string containing the internal profile information stored in
  647. an ICC tag.
  648. :exception PyCMSError:
  649. """
  650. try:
  651. # add an extra newline to preserve pyCMS compatibility
  652. if not isinstance(profile, ImageCmsProfile):
  653. profile = ImageCmsProfile(profile)
  654. return (profile.profile.copyright or "") + "\n"
  655. except (AttributeError, OSError, TypeError, ValueError) as v:
  656. raise PyCMSError(v) from v
  657. def getProfileManufacturer(profile):
  658. """
  659. (pyCMS) Gets the manufacturer for the given profile.
  660. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
  661. :exc:`PyCMSError` is raised.
  662. If an error occurs while trying to obtain the manufacturer tag, a
  663. :exc:`PyCMSError` is raised.
  664. Use this function to obtain the information stored in the profile's
  665. manufacturer tag.
  666. :param profile: EITHER a valid CmsProfile object, OR a string of the
  667. filename of an ICC profile.
  668. :returns: A string containing the internal profile information stored in
  669. an ICC tag.
  670. :exception PyCMSError:
  671. """
  672. try:
  673. # add an extra newline to preserve pyCMS compatibility
  674. if not isinstance(profile, ImageCmsProfile):
  675. profile = ImageCmsProfile(profile)
  676. return (profile.profile.manufacturer or "") + "\n"
  677. except (AttributeError, OSError, TypeError, ValueError) as v:
  678. raise PyCMSError(v) from v
  679. def getProfileModel(profile):
  680. """
  681. (pyCMS) Gets the model for the given profile.
  682. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
  683. :exc:`PyCMSError` is raised.
  684. If an error occurs while trying to obtain the model tag,
  685. a :exc:`PyCMSError` is raised.
  686. Use this function to obtain the information stored in the profile's
  687. model tag.
  688. :param profile: EITHER a valid CmsProfile object, OR a string of the
  689. filename of an ICC profile.
  690. :returns: A string containing the internal profile information stored in
  691. an ICC tag.
  692. :exception PyCMSError:
  693. """
  694. try:
  695. # add an extra newline to preserve pyCMS compatibility
  696. if not isinstance(profile, ImageCmsProfile):
  697. profile = ImageCmsProfile(profile)
  698. return (profile.profile.model or "") + "\n"
  699. except (AttributeError, OSError, TypeError, ValueError) as v:
  700. raise PyCMSError(v) from v
  701. def getProfileDescription(profile):
  702. """
  703. (pyCMS) Gets the description for the given profile.
  704. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
  705. :exc:`PyCMSError` is raised.
  706. If an error occurs while trying to obtain the description tag,
  707. a :exc:`PyCMSError` is raised.
  708. Use this function to obtain the information stored in the profile's
  709. description tag.
  710. :param profile: EITHER a valid CmsProfile object, OR a string of the
  711. filename of an ICC profile.
  712. :returns: A string containing the internal profile information stored in an
  713. ICC tag.
  714. :exception PyCMSError:
  715. """
  716. try:
  717. # add an extra newline to preserve pyCMS compatibility
  718. if not isinstance(profile, ImageCmsProfile):
  719. profile = ImageCmsProfile(profile)
  720. return (profile.profile.profile_description or "") + "\n"
  721. except (AttributeError, OSError, TypeError, ValueError) as v:
  722. raise PyCMSError(v) from v
  723. def getDefaultIntent(profile):
  724. """
  725. (pyCMS) Gets the default intent name for the given profile.
  726. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
  727. :exc:`PyCMSError` is raised.
  728. If an error occurs while trying to obtain the default intent, a
  729. :exc:`PyCMSError` is raised.
  730. Use this function to determine the default (and usually best optimized)
  731. rendering intent for this profile. Most profiles support multiple
  732. rendering intents, but are intended mostly for one type of conversion.
  733. If you wish to use a different intent than returned, use
  734. ImageCms.isIntentSupported() to verify it will work first.
  735. :param profile: EITHER a valid CmsProfile object, OR a string of the
  736. filename of an ICC profile.
  737. :returns: Integer 0-3 specifying the default rendering intent for this
  738. profile.
  739. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  740. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  741. ImageCms.Intent.SATURATION = 2
  742. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  743. see the pyCMS documentation for details on rendering intents and what
  744. they do.
  745. :exception PyCMSError:
  746. """
  747. try:
  748. if not isinstance(profile, ImageCmsProfile):
  749. profile = ImageCmsProfile(profile)
  750. return profile.profile.rendering_intent
  751. except (AttributeError, OSError, TypeError, ValueError) as v:
  752. raise PyCMSError(v) from v
  753. def isIntentSupported(profile, intent, direction):
  754. """
  755. (pyCMS) Checks if a given intent is supported.
  756. Use this function to verify that you can use your desired
  757. ``intent`` with ``profile``, and that ``profile`` can be used for the
  758. input/output/proof profile as you desire.
  759. Some profiles are created specifically for one "direction", can cannot
  760. be used for others. Some profiles can only be used for certain
  761. rendering intents, so it's best to either verify this before trying
  762. to create a transform with them (using this function), or catch the
  763. potential :exc:`PyCMSError` that will occur if they don't
  764. support the modes you select.
  765. :param profile: EITHER a valid CmsProfile object, OR a string of the
  766. filename of an ICC profile.
  767. :param intent: Integer (0-3) specifying the rendering intent you wish to
  768. use with this profile
  769. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  770. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  771. ImageCms.Intent.SATURATION = 2
  772. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  773. see the pyCMS documentation for details on rendering intents and what
  774. they do.
  775. :param direction: Integer specifying if the profile is to be used for
  776. input, output, or proof
  777. INPUT = 0 (or use ImageCms.Direction.INPUT)
  778. OUTPUT = 1 (or use ImageCms.Direction.OUTPUT)
  779. PROOF = 2 (or use ImageCms.Direction.PROOF)
  780. :returns: 1 if the intent/direction are supported, -1 if they are not.
  781. :exception PyCMSError:
  782. """
  783. try:
  784. if not isinstance(profile, ImageCmsProfile):
  785. profile = ImageCmsProfile(profile)
  786. # FIXME: I get different results for the same data w. different
  787. # compilers. Bug in LittleCMS or in the binding?
  788. if profile.profile.is_intent_supported(intent, direction):
  789. return 1
  790. else:
  791. return -1
  792. except (AttributeError, OSError, TypeError, ValueError) as v:
  793. raise PyCMSError(v) from v
  794. def versions():
  795. """
  796. (pyCMS) Fetches versions.
  797. """
  798. return VERSION, core.littlecms_version, sys.version.split()[0], Image.__version__