将 4 个十六进制字节转换为 RGBA 颜色
Converting 4 hex bytes to RGBA color
我有一个 512x512 图像文件,每 4 个字节用于一个 RGBA 像素。这是一个例子:
1F 8B 08 00
第一个(R)、第二个(G)和第三个(B)字节代表RGB值,每个值的范围从0到255。最后一个字节(A)代表alpha通道,也从0 到 255。如果我想要一个不透明的像素,我必须用 FF 替换最后一个字节(转换为十进制时为 255)。将 4 个字节转换为 RGBA 后,我可以使用 PIL 创建图像,前 4 个字节是位于左上角的像素。
现在这是 4 个字节,手动转换为 1x1 RGBA 像素:
image
这里是像素的 RGBA 值,基于 4 个字节:
199(R) 239(G) 125(B) 213(A)
基本上每个字节都应该转换成0到255之间的数字,每4个字节是一个RGBA值。我可以将这些值放入一个元组中,将每 4 个值迭代为一个 RGBA 像素,第一个像素位于图像的左上角。
最简单的阅读方式是使用 Numpy:
import numpy as np
from PIL import Image
# Load (unzipped) binary file into Numpy array and reshape
na = np.fromfile('a.rgba',dtype=np.uint8).reshape((512,512,4))
# Make into PIL Image and save
Image.fromarray(na).save('result.png')
顺便说一句,你真的不需要任何 Python,你可以在终端中使用 ImageMagick:
magick -depth 8 -size 512x512 RGBA:yourFile.rgba -auto-level result.png
我添加 -auto-level
只是为了好玩,以拉伸对比度。
如果你不使用 Numpy,这里有第三种方法:
from PIL import Image
# Slurp entire binary file
with open('image.rgba', 'rb') as file:
data = file.read()
# Make into PIL Image with raw decoder
im = Image.frombuffer('RGBA', (512,512), data, 'raw', 'RGBA', 0, 1)
我有一个 512x512 图像文件,每 4 个字节用于一个 RGBA 像素。这是一个例子:
1F 8B 08 00
第一个(R)、第二个(G)和第三个(B)字节代表RGB值,每个值的范围从0到255。最后一个字节(A)代表alpha通道,也从0 到 255。如果我想要一个不透明的像素,我必须用 FF 替换最后一个字节(转换为十进制时为 255)。将 4 个字节转换为 RGBA 后,我可以使用 PIL 创建图像,前 4 个字节是位于左上角的像素。
现在这是 4 个字节,手动转换为 1x1 RGBA 像素: image
这里是像素的 RGBA 值,基于 4 个字节:
199(R) 239(G) 125(B) 213(A)
基本上每个字节都应该转换成0到255之间的数字,每4个字节是一个RGBA值。我可以将这些值放入一个元组中,将每 4 个值迭代为一个 RGBA 像素,第一个像素位于图像的左上角。
最简单的阅读方式是使用 Numpy:
import numpy as np
from PIL import Image
# Load (unzipped) binary file into Numpy array and reshape
na = np.fromfile('a.rgba',dtype=np.uint8).reshape((512,512,4))
# Make into PIL Image and save
Image.fromarray(na).save('result.png')
顺便说一句,你真的不需要任何 Python,你可以在终端中使用 ImageMagick:
magick -depth 8 -size 512x512 RGBA:yourFile.rgba -auto-level result.png
我添加 -auto-level
只是为了好玩,以拉伸对比度。
如果你不使用 Numpy,这里有第三种方法:
from PIL import Image
# Slurp entire binary file
with open('image.rgba', 'rb') as file:
data = file.read()
# Make into PIL Image with raw decoder
im = Image.frombuffer('RGBA', (512,512), data, 'raw', 'RGBA', 0, 1)