BGR565数据转换为图片预览

评价:
5
(1用户)

最近遇到几个文件,使用的图像编码是BGR565格式。所用包为PIL,python3以上似乎不支持了,可以用另一个pillow代替,大神魔改的版本。功能一样

BGR与RGB相近,无非就是将B与R的二进制调换位置,565格式代表共16位数据。

首先将文件二进制数据读取,并保存为txt文档。然后使用py编写程序进行数据解析。

from PIL import Image, ImageDraw


w = 236  # 宽
h = 155  # 高

FileAdd = "D:\\1.txt"
# 用于转换的
HEX = {}
HEX1 = {}
RGB = []


def Hex_To_Dec(hex):
    if hex == '0':
        rx = 0
    elif hex == '1':
        rx = 1
    elif hex == '2':
        rx = 2
    elif hex == '3':
        rx = 3
    elif hex == '4':
        rx = 4
    elif hex == '5':
        rx = 5
    elif hex == '6':
        rx = 6
    elif hex == '7':
        rx = 7
    elif hex == '8':
        rx = 8
    elif hex == '9':
        rx = 9
    elif hex == 'A':
        rx = 10
    elif hex == 'B':
        rx = 11
    elif hex == 'C':
        rx = 12
    elif hex == 'D':
        rx = 13
    elif hex == 'E':
        rx = 14
    elif hex == 'F':
        rx = 15
    else:
        return (100)
    return (re)


# main()
if __name__ == "__main__":
    f = open(FileAdd, encoding="utf-8")  # 打开文件
    print("正在解析" + FileAdd + "的数据,合成文件名为" + str(w) + "*" + str(h) + "的图片")
    x = 0
    z = 0
    for x in range(w * h * 60):  # 进制转换 16-10
        f.seek(z + 0, 0)
        f1 = f.read(1)
        f.seek(z + 1, 0)
        f2 = f.read(1)
        f.seek(z + 3, 0)
        f3 = f.read(1)
        f.seek(z + 4, 0)
        f4 = f.read(1)
        z = z + 6

        HEX1[x] = ((Hex_To_Dec(f1) << 12) + (Hex_To_Dec(f2) << 8) + (Hex_To_Dec(f3) << 4) + Hex_To_Dec(f4))
        a = bin(HEX1[x])  #BRG与RGB互相转换
        a1 = a[2:7]
        a2 = a[7:13]
        a3 = a[13:18]
        c = a3 + a2 + a1
        HEX[x] = int(c,2)

        if z >= (w * h * 6):
            break
    f.close()  # 关闭文件
    x = 0
    for x in range(len(HEX)):  
        r = (((HEX[x] & 0xF800) >> 8))
        g = (((HEX[x] & 0x7E0) >> 3))
        b = (((HEX[x] & 0x1F) << 3))
        rgb = (r, g, b)
        RGB.append(rgb)

    # print(RGB)
    # print(HEX)

    image = Image.new('RGB', (w, h), (255, 255, 255))  # 创建新图片对象

    draw = ImageDraw.Draw(image)  # 创建Draw对象用于绘制新图:

    x = 0
    y = 0
    i = 0

    for y in range(h):  # 填充每个像素并对对应像素填上RGB值:
        for x in range(w):
            draw.point((x, y), fill=RGB[i])
            i = i + 1

    image.save('D:\\2.jpeg', 'jpeg')  # 将转换后的图像保存到D盘中
    image.show()  # 查看图像

本文为原创文章,转载请注明出处!

注册并通过认证的用户才可以进行评价!

admin:支持一下,感谢分享!,+10,  

发表评论