Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/sphinx-doc/sphinx.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGeorg Brandl <georg@python.org>2008-12-10 02:43:11 +0300
committerGeorg Brandl <georg@python.org>2008-12-10 02:43:11 +0300
commitb7a2491e216d0e52a7f907fd2556c3d07fedf8e7 (patch)
treef67029df63c633a61610f5730d178b76f5a5c173 /sphinx/util/png.py
parent0d88e4b02058c36820247f9f530feb0ff6fb9d0d (diff)
#65: Store depth information in PNG images themselves.
Diffstat (limited to 'sphinx/util/png.py')
-rw-r--r--sphinx/util/png.py58
1 files changed, 58 insertions, 0 deletions
diff --git a/sphinx/util/png.py b/sphinx/util/png.py
new file mode 100644
index 000000000..a22acba2e
--- /dev/null
+++ b/sphinx/util/png.py
@@ -0,0 +1,58 @@
+# -*- coding: utf-8 -*-
+"""
+ sphinx.util.png
+ ~~~~~~~~~~~~~~~
+
+ PNG image manipulation helpers.
+
+ :copyright: 2008 by Georg Brandl.
+ :license: BSD.
+"""
+
+import struct
+import binascii
+
+LEN_IEND = 12
+LEN_DEPTH = 22
+
+DEPTH_CHUNK_LEN = struct.pack('!i', 10)
+DEPTH_CHUNK_START = 'tEXtDepth\x00'
+IEND_CHUNK = '\x00\x00\x00\x00IEND\xAE\x42\x60\x82'
+
+
+def read_png_depth(filename):
+ """
+ Read the special tEXt chunk indicating the depth from a PNG file.
+ """
+ result = None
+ f = open(filename, 'rb')
+ try:
+ f.seek(- (LEN_IEND + LEN_DEPTH), 2)
+ depthchunk = f.read(LEN_DEPTH)
+ if not depthchunk.startswith(DEPTH_CHUNK_LEN + DEPTH_CHUNK_START):
+ # either not a PNG file or not containing the depth chunk
+ return None
+ result = struct.unpack('!i', depthchunk[14:18])[0]
+ finally:
+ f.close()
+ return result
+
+
+def write_png_depth(filename, depth):
+ """
+ Write the special tEXt chunk indicating the depth to a PNG file.
+ The chunk is placed immediately before the special IEND chunk.
+ """
+ data = struct.pack('!i', depth)
+ f = open(filename, 'r+b')
+ try:
+ # seek to the beginning of the IEND chunk
+ f.seek(-LEN_IEND, 2)
+ # overwrite it with the depth chunk
+ f.write(DEPTH_CHUNK_LEN + DEPTH_CHUNK_START + data)
+ # calculate the checksum over chunk name and data
+ f.write(struct.pack('!i', binascii.crc32(DEPTH_CHUNK_START + data)))
+ # replace the IEND chunk
+ f.write(IEND_CHUNK)
+ finally:
+ f.close()