论坛元老
- 积分
- 6661
- 金钱
- 6661
- 注册时间
- 2016-5-29
- 在线时间
- 909 小时
|
发表于 2024-11-4 16:40:40
|
显示全部楼层
# BMP 单色文件 转数组 , python 代码.
#import tkinter as tk
import pyperclip
import os
# import shutil
from PIL import Image #, ImageDraw, ImageFont
#from tkinter.messagebox import showinfo
# def print_hex4(buf):
# s = [ "0x" + hex(tt)[2:].zfill(4) for tt in buf]
# print ( ", ".join(s))
# def print_hex(buf):
# s = [ "0x" + hex(tt)[2:].zfill(2) for tt in buf]
# print ( ", ".join(s))
# def dis_out(s):
# root = tk.Tk()
# root.geometry('1600x1000+0+0')
# root.title('图片转C语言')
# # def Take_input():
# # msg = text.get("1.7", "end")
# # showinfo(title='欢迎访问', message=msg)
# text = tk.Text(root,width=132, height=44, font=("宋体", 16))
# text.pack(padx=1, pady=1)
# text.insert(tk.INSERT, s)
# # Display = tk.Button(root, height = 2, width = 20, text ="读取", command = lambda:Take_input())
# # Display.pack()
# root.mainloop()
outbuf=[]
def work(fs):
outbuf.clear()
image = Image.open(fs)
# 显示图片
# image.show()
# 获取图像的大小
width, height = image.size
# print("const uc pic [ ",width,"/8 * ",height ,']=')
# 转换为RGB模式
image = image.convert('RGB')
# 获取像素RGB值
pixels = image.load()
def app2buf(n1,color):
global outbuf
color &= 0xff
if n1 & 0xff00:
outbuf.append ((n1>>8)&0xff)
n1 &= 0xff
n1 <<= 8
n1 |= color
outbuf.append (n1)
# 遍历所有像素点,8个像素 组成一个字节. 从上往下,逐行扫描,高位在前,结果保存在BF[]数组中.
n = 0
bf = [0] * (width//8*height)
buf = 0
for y in range(height):
for x in range(width):
r, g, b = pixels[x, y]
buf <<=1
if( (r+ g+ b ) != 0 ):
buf |= 1
n += 1
if n & 7 == 0:
bf[(n >> 3)-1] = buf & 0xff
# print_hex(bf)
# 压缩算法
n=0
lbf=bf[0]
for i in bf:
if lbf==i: # 相同颜色的数量
n += 1
else:
if n > 0 :
app2buf(n,lbf) # 颜色 不同时,输出 数量颜色 到 outbuf 数组 .
n = 1
lbf = i
if n > 0 :
app2buf(n,lbf)
outbuf.append (0) # 压缩 结束符
# 转 C 语言
df=""
df += '\nconst us pic []= // ' + fs + "\n"
df += '{\n'
n = 0
for i in outbuf:
s = "0x" + hex(i)[2:].zfill(4)
df += s + ","
n+=1
if n >= 16:
n = 0
df += '\n'
df += "// 压缩比 = " + "%.3f" %( outbuf.__len__()*2/ bf.__len__()) +"\n"
df += '};\n'
if (outbuf.__len__()*2/ bf.__len__() > 1.00 ): # 压缩比 大于1 就直接输出图片.
df = ""
df += '\nconst uc pic []= //'+ fs + "\n"
df += '{\n'
n = 0
for i in bf:
s = "0x" + hex(i)[2:].zfill(2)
df += s +','
n += 1
if n >= 16:
n = 0
df += '\n'
df += '};\n'
pyperclip.copy(df) # 复制到系统的剪切板
print(df)
# dis_out(df)
run_flag = True
while(run_flag == True):
filename = input("请输入图片的文件路径:")
filename = filename.replace('\"',"")
filename = filename.replace("'","")
filename = filename.lower()
if filename == "exit":
run_flag = False
else:
if (os.path.exists(filename) == False):
print("输入的名称不存在,请重新输入")
else:
if len(filename) <= 4:
print("输入错误,请重新输入")
else:
print(filename[-4:])
if filename[-4:] != ".bmp" and filename[-4:] != ".jpg":
print("文件类型不是图片")
else:
work(filename)
|
|