- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我知道这看起来太简单了,但我找不到直接的解决方案。
保存后,itxt 应该再次压缩。
最佳答案
它并不像您目测的那么简单。如果是,您可能已经发现没有直接的解决方案。
让我们从基础开始。
一个重要的问题,因为修改现有的 PNG 文件是一项艰巨的任务。阅读它的文档,开始时并不顺利:
PNG: Chunk by Chunk
Ancillary Chunks
..iTXt
Ignored when reading. Not generated.
( https://pythonhosted.org/pypng/chunk.html )
但在那一页的下方,救恩!
Non-standard Chunks
Generally it is not possible to generate PNG images with any other chunk types. When reading a PNG image, processing it using the chunk interface,png.Reader.chunks
, will allow any chunk to be processed (by user code).
所以我所要做的就是编写这个“用户代码”,PyPNG 可以完成剩下的工作。 (糟糕。)
iTXt
block 呢?让我们看看您感兴趣的内容。
4.2.3.3. iTXt International textual data
.. the textual data is in the UTF-8 encoding of the Unicode character set instead of Latin-1. This chunk contains:
Keyword: 1-79 bytes (character string)
Null separator: 1 byte
Compression flag: 1 byte
Compression method: 1 byte
Language tag: 0 or more bytes (character string)
Null separator: 1 byte
Translated keyword: 0 or more bytes
Null separator: 1 byte
Text: 0 or more bytes
( http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.iTXt )
我看起来很清楚。可选的压缩应该不是问题,因为
.. [t]he only value presently defined for the compression method byte is 0, meaning zlib ..
而且我非常有信心,Python 已经存在可以为我做这件事的东西。
然后回到 PyPNG 的 block 处理。
PyPNG 提供了一个迭代器,因此检查 PNG 是否包含 iTXt
block 确实很容易:
chunks()
Return an iterator that will yield each chunk as a (chunktype, content) pair.
( https://pythonhosted.org/pypng/png.html?#png.Reader.chunks )
那么让我们以交互模式编写一些代码并检查一下。我从 http://pmt.sourceforge.net/itxt/ 得到了一张样本图片, 为方便起见在此重复。 (如果此处未保存iTXt
数据,请下载并使用原始数据。)
>>> import png
>>> imageFile = png.Reader("itxt.png")
>>> print imageFile
<png.Reader instance at 0x10ae1cfc8>
>>> for c in imageFile.chunks():
... print c[0],len(c[1])
...
IHDR 13
gAMA 4
sBIT 4
pCAL 44
tIME 7
bKGD 6
pHYs 9
tEXt 9
iTXt 39
IDAT 4000
IDAT 831
zTXt 202
iTXt 111
IEND 0
成功!
回信呢?好吧,PyPNG 通常用于创建完整的图像,但幸运的是,它还提供了一种从自定义 block 显式创建图像的方法:
png.write_chunks(out, chunks)
Create a PNG file by writing out the chunks.
因此我们可以遍历 block ,更改所需的 block ,然后写回修改后的 PNG。
iTXt
数据这本身就是一项任务。数据格式描述的很好,但是不适合Python原生的unpack
和pack
方法。所以我们必须自己发明一些东西。
文本字符串以 ASCIIZ 格式存储:以零字节结尾的字符串。我们需要一个小函数来拆分第一个 0
:
def cutASCIIZ(str):
end = str.find(chr(0))
if end >= 0:
result = str[:end]
return [str[:end],str[end+1:]]
return ['',str]
这个快速而简单的函数返回一个 [before, after] 对的数组,并丢弃零本身。
为了尽可能透明地处理 iTXt
数据,我将其设为一个类:
class Chunk_iTXt:
def __init__(self, chunk_data):
tmp = cutASCIIZ(chunk_data)
self.keyword = tmp[0]
if len(tmp[1]):
self.compressed = ord(tmp[1][0])
else:
self.compressed = 0
if len(tmp[1]) > 1:
self.compressionMethod = ord(tmp[1][1])
else:
self.compressionMethod = 0
tmp = tmp[1][2:]
tmp = cutASCIIZ(tmp)
self.languageTag = tmp[0]
tmp = tmp[1]
tmp = cutASCIIZ(tmp)
self.languageTagTrans = tmp[0]
if self.compressed:
if self.compressionMethod != 0:
raise TypeError("Unknown compression method")
self.text = zlib.decompress(tmp[1])
else:
self.text = tmp[1]
def pack (self):
result = self.keyword+chr(0)
result += chr(self.compressed)
result += chr(self.compressionMethod)
result += self.languageTag+chr(0)
result += self.languageTagTrans+chr(0)
if self.compressed:
if self.compressionMethod != 0:
raise TypeError("Unknown compression method")
result += zlib.compress(self.text)
else:
result += self.text
return result
def show (self):
print 'iTXt chunk contents:'
print ' keyword: "'+self.keyword+'"'
print ' compressed: '+str(self.compressed)
print ' compression method: '+str(self.compressionMethod)
print ' language: "'+self.languageTag+'"'
print ' tag translation: "'+self.languageTagTrans+'"'
print ' text: "'+self.text+'"'
因为这使用了 zlib
,所以它需要在程序的顶部有一个 import zlib
。
类构造函数接受“太短”的字符串,在这种情况下它将对所有未定义的内容使用默认值。
show
方法列出用于调试目的的数据。
有了所有这些,现在检查、修改和添加 iTXt
block 终于简单了:
import png
import zlib
# insert helper and class here
sourceImage = png.Reader("itxt.png")
chunkList = []
for chunk in sourceImage.chunks():
if chunk[0] == 'iTXt':
itxt = Chunk_iTXt(chunk[1])
itxt.show()
# modify existing data
if itxt.keyword == 'Author':
itxt.text = 'Rad Lexus'
itxt.compressed = 1
chunk = [chunk[0], itxt.pack()]
chunkList.append (chunk)
# append new data
newData = Chunk_iTXt('')
newData.keyword = 'Custom'
newData.languageTag = 'nl'
newData.languageTagTrans = 'Aangepast'
newData.text = 'Dat was leuk.'
chunkList.insert (-1, ['iTXt', newData.pack()])
with open("foo.png", "wb") as file:
png.write_chunks(file, chunkList)
当添加一个全新的 block 时,注意不要append
它,因为那样它会出现在所需的最后一个 IEND
block ,这是一个错误。我没有尝试,但您也不应该将它插入到所需的第一个 IHDR
block 之前,或者(正如 Glenn Randers-Pehrson 评论的那样)插入连续的 IDAT
block 之间。
请注意,根据规范,iTXt
中的所有文本都应采用 UTF8 编码。
关于python - 如何在 python 中修改现有文件的压缩 itxt 记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37068414/
我正在处理一组标记为 160 个组的 173k 点。我想通过合并最接近的(到 9 或 10 个组)来减少组/集群的数量。我搜索过 sklearn 或类似的库,但没有成功。 我猜它只是通过 knn 聚类
我有一个扁平数字列表,这些数字逻辑上以 3 为一组,其中每个三元组是 (number, __ignored, flag[0 or 1]),例如: [7,56,1, 8,0,0, 2,0,0, 6,1,
我正在使用 pipenv 来管理我的包。我想编写一个 python 脚本来调用另一个使用不同虚拟环境(VE)的 python 脚本。 如何运行使用 VE1 的 python 脚本 1 并调用另一个 p
假设我有一个文件 script.py 位于 path = "foo/bar/script.py"。我正在寻找一种在 Python 中通过函数 execute_script() 从我的主要 Python
这听起来像是谜语或笑话,但实际上我还没有找到这个问题的答案。 问题到底是什么? 我想运行 2 个脚本。在第一个脚本中,我调用另一个脚本,但我希望它们继续并行,而不是在两个单独的线程中。主要是我不希望第
我有一个带有 python 2.5.5 的软件。我想发送一个命令,该命令将在 python 2.7.5 中启动一个脚本,然后继续执行该脚本。 我试过用 #!python2.7.5 和http://re
我在 python 命令行(使用 python 2.7)中,并尝试运行 Python 脚本。我的操作系统是 Windows 7。我已将我的目录设置为包含我所有脚本的文件夹,使用: os.chdir("
剧透:部分解决(见最后)。 以下是使用 Python 嵌入的代码示例: #include int main(int argc, char** argv) { Py_SetPythonHome
假设我有以下列表,对应于及时的股票价格: prices = [1, 3, 7, 10, 9, 8, 5, 3, 6, 8, 12, 9, 6, 10, 13, 8, 4, 11] 我想确定以下总体上最
所以我试图在选择某个单选按钮时更改此框架的背景。 我的框架位于一个类中,并且单选按钮的功能位于该类之外。 (这样我就可以在所有其他框架上调用它们。) 问题是每当我选择单选按钮时都会出现以下错误: co
我正在尝试将字符串与 python 中的正则表达式进行比较,如下所示, #!/usr/bin/env python3 import re str1 = "Expecting property name
考虑以下原型(prototype) Boost.Python 模块,该模块从单独的 C++ 头文件中引入类“D”。 /* file: a/b.cpp */ BOOST_PYTHON_MODULE(c)
如何编写一个程序来“识别函数调用的行号?” python 检查模块提供了定位行号的选项,但是, def di(): return inspect.currentframe().f_back.f_l
我已经使用 macports 安装了 Python 2.7,并且由于我的 $PATH 变量,这就是我输入 $ python 时得到的变量。然而,virtualenv 默认使用 Python 2.6,除
我只想问如何加快 python 上的 re.search 速度。 我有一个很长的字符串行,长度为 176861(即带有一些符号的字母数字字符),我使用此函数测试了该行以进行研究: def getExe
list1= [u'%app%%General%%Council%', u'%people%', u'%people%%Regional%%Council%%Mandate%', u'%ppp%%Ge
这个问题在这里已经有了答案: Is it Pythonic to use list comprehensions for just side effects? (7 个答案) 关闭 4 个月前。 告
我想用 Python 将两个列表组合成一个列表,方法如下: a = [1,1,1,2,2,2,3,3,3,3] b= ["Sun", "is", "bright", "June","and" ,"Ju
我正在运行带有最新 Boost 发行版 (1.55.0) 的 Mac OS X 10.8.4 (Darwin 12.4.0)。我正在按照说明 here构建包含在我的发行版中的教程 Boost-Pyth
学习 Python,我正在尝试制作一个没有任何第 3 方库的网络抓取工具,这样过程对我来说并没有简化,而且我知道我在做什么。我浏览了一些在线资源,但所有这些都让我对某些事情感到困惑。 html 看起来
我是一名优秀的程序员,十分优秀!