How can I create a PNG image file from a list of pixel values in Python?

前端 未结 2 1346
野趣味
野趣味 2021-01-19 00:58

I can generate a list of pixel values from an existing image file using a procedure like the following:

from PIL import Image
image = Image.open(\"test.png\"         


        
2条回答
  •  温柔的废话
    2021-01-19 01:47

    You can you cairo. Pretty easy.

    #!/usr/bin/python
    
    # Extracting pixels from an image ------
    from PIL import Image
    image = Image.open("test.png")
    pixels = list(image.getdata())
    width, height = image.size
    pixels = [pixels[i * width:(i + 1) * width] for i in xrange(height)]
    
    
    # Putting pixels back to an image ------
    
    import cairo
    
    Width=len(pixels[0])
    Height=len(pixels)
    
    surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, Width, Height)
    context = cairo.Context (surface)
    
    y=0
    for row in pixels:
        x=0
        for rgb in row:
            r=rgb[0] /255.0
            g=rgb[1] /255.0
            b=rgb[2] /255.0
            context.set_source_rgb(r, g, b)
            context.rectangle(x, y, 1, 1)
            context.fill()
            x+=1
        y+=1
    
    surface.write_to_png ("out.png") # Output to PNG
    

提交回复
热议问题