今天学习ctf遇到了从rgb数据构造图片的题,顺便学一下python的Image模块吧
具体文档
属性
# 图片大小
width, height = im.size
# 文件名包含路径
print(im.filename)
# 文件类型png/jpg/bmt
print(im.format)
# 模式rgb/rgba/cmyk
print(im.mode)
# im.width
# im.height
方法
from PIL import Image
from io import BytesIO
# 对于彩色图像,不管其图像格式是PNG,还是BMP,或者JPG,在PIL中,使用Image模块的open()函数打开后,返回的图像对象的模式都是“RGB”。
# 而对于灰度图像,不管其图像格式是PNG,还是BMP,或者JPG,打开后,其模式为“L”
im = Image.open("misc/tp/txt.png")
# 从二进制打开图片
im = Image.open(BytesIO("misc/tp/txt.bin"))
# 构造图像
width, height = 128, 128
color = (0, 235, 255)
im = Image.new('RGB', (width, height), color) #RGB
im = Image.new('1', (width, height),1) #1是白0是黑
im = Image.new('L', (width, height), 120) # 128位灰度图
im = Image.new('RGBA', (width, height), (255,255,128,128)) # RGBA
# 得到i,j位置的像素值
im.getpixel((i, j))
# 通过像素修改图像
x, y = (1, 2)
color = (0, 0, 0)
im.putpixel((x, y), color)
# 展示图片
im.show()
# 保存图片
im.save("misc/tp/txt.png")
#得到png,jpg,bmp格式图片的每一帧的RGB
width,height=im.size
pix = [im.getpixel((i, j)) for i in range(width) for j in range(height)]
print(pix)
# 旋转45度
im = im.rotate(45)
# 等比缩放
size = 128, 128
im.thumbnail(size)
# 按给定值缩放
im = im.resize((120, 12))
# 图片类型转换
im.convert("1")
im.convert("L")
im.convert("RGB")
类型转换这个博客写的挺好的:
https://blog.csdn.net/icamera0/article/details/50843172
# split分割RGB时,按照RGB的三原色,返回三个图像。其他类似
imm=im.split()
imm[0].show()
# 裁剪矩形
left,top,right,bottm=(1,2,100,100)
im=im.crop((left,top,right,bottm))
# 转换成比特流
im.tobytes()
ctf 练习
练习一下从RGB数据恢复成图片
https://pan.baidu.com/s/1KP9BiRn8EaSnB9s9iSEJlg
密码: awic
答案
from PIL import Image
file_txt = open("misc/tp/pic.txt", "r")
str_pix = file_txt.read().split("\n")
width, height = 0, 0
# Get the width and height of the image
for i in str_pix:
if int(i.split(" ")[0]) > width:
width = int(i.split(" ")[0])
if int(i.split(" ")[1]) > height:
height = int(i.split(" ")[1])
# Output the width and height
print ("Width: ", width, " Height: ", height)
img = Image.new("RGB", (width,height))
# Write pixel to new image file:
# pixTuple(R, G, B, A)
# x -> width, y -> height, R -> red, G -> green, B -> blue, A -> transparency
for i in str_pix:
x = int(i.split(" ")[0])
y = int(i.split(" ")[1])
R = int(i.split(" ")[2])
G = int(i.split(" ")[3])
B = int(i.split(" ")[4])
pixTuple = (R, G, B, 0)
img.putpixel((x-1, y-1), pixTuple)
# Save the image file
img.save("output.png")