png图片转RGBA数组,保存到头文件

import os,sys
from PIL import Image

def get_arr_img(fn,id):
  infile = fn
  outfile = id
  outfile +=str(".c")
  im=Image.open(infile)
  print(im.size[1])
  img_arr = ""
  img_arr = str("const unsigned char gImage_{id}[] = {{\n"
                  .format(id=id, w=im.width, h=im.height))
  print("read %s\nImage Width:%d Height:%d" % (infile, im.size[0], im.size[1]))
  f = open(outfile, "w")
 # pix = im.load()  #load pixel array
  for h in range(im.size[1]):
    for w in range(im.size[0]):
      R = im.getpixel((w, h))[0]
      G = im.getpixel((w, h))[1]
      B = im.getpixel((w, h))[2]
      A = im.getpixel((w, h))[3]
      img_arr += str(B)
      img_arr += str(",")
      img_arr += str(G)
      img_arr += str(",")
      img_arr += str(R)
      img_arr += str(",")
      img_arr += str(A)
      img_arr += str(",")
    img_arr += str("\n")
  img_arr += str("};")
  f.write(img_arr)
  f.close()
  print("write to %s" % outfile)


def main():
  Path="./"
  img_dir = os.listdir(Path)
  for img in img_dir:
    if img.endswith('.png'):
      PngPath= os.path.join(Path,img)
      print(PngPath)
      get_arr_img(PngPath,img.split(".")[0])
if __name__ == "__main__":
	sys.exit(main())


png图片转RGBA数组,保存到头文件_第1张图片

你可能感兴趣的:(python)