generate_text(size: , output: ) :def int str -> None
"""
生成特定长度的随机文本
:param size: 生成的随机文本的长度
:param output: 输出文件名称
"""
(output, ) fd:with open "wb" as
current_size: sizeint =
current_size :while > 0
# 每次生成 4K
batch: ( , current_size)int = min 4096
fd.write( .join([random.choice(string.printable) _ (batch)]).encode())"" for in range
current_size batch-=
( output stat(output) st_size )print f"the generated text is store in { }, file size is {os. . / 1024} KB"
main() :def -> None
parser: OptionParser OptionParser(usage )= ="python %prog options..."
parser.add_option( , , dest , default , ,"-t" "--type" ="type" ="txt" type=str
)help="the type of generated file, including jpg, png, gif, txt"
parser.add_option( , , dest , default , ,"-w" "--width" ="width" =200 type=int
)help="the width of image, if type is image"
parser.add_option( , , dest , default , ,"-H" "--height" ="height" =200 type=int
)help="the height of image, if type is image"
parser.add_option( , , dest , default , ,"-s" "--size" ="size" =1024 type=int
)help="the size of generated file, in bytes"
parser.add_option( , , dest , default , ,"-o" "--output" ="output" ="a" type=str
)help="output file name"
parser.add_option( , , dest , default , ,"-n" "--num-frames" ="num_frames" =10 type=int
)help="the frame number of generated GIF image"
options, _ parser.parse_args()=
_, ext os.path.splitext(options.output)=
options. .lower() :if type == "jpg"
ext [ , , ]:if not in ".jpg" "jpeg" ".jfif"
options.output += ".jpg"
generate_jpg(options.width, options.height, options.output)
return
options. .lower() :if type == "png"
ext [ ]:if not in ".png"
options.output += ".png"
generate_png(options.width, options.height, options.output)
return
options. .lower() :if type == "gif"
ext [ ]:if not in ".gif"
options.output += ".gif"
generate_gif(options.width, options.height, options.num_frames, options.output)
return
options. .lower() :if type == "txt"
ext [ ]:if not in ".txt"
options.output += ".txt"
generate_text(options.size, options.output)
:if __name__ == "__main__"
main()
比如,执行如下命令将生成 100x100 的 GIF 图片:
python3 generate_image.py -t gif -o 100x100.gif --width 100 --height 100 --num-frames 20