Shiatryx
Shiatryx

Reputation: 41

With PyPNG, how do I read a PNG with it?

This seems like a dumb question at first--just read the docs!--but I did, and can't figure out how I can read a file, and get an RGB value. Simply, it isn't clear what anything means.

Could someone please show me how I could read a file correctly, with RGB data?

Upvotes: 3

Views: 2707

Answers (2)

Bsd-us
Bsd-us

Reputation: 11

Found no answer to this useful question so here's what I came up with (docs didn't help) :

# Reading the png metadata
image = png.Reader(filename='test.png').asDirect()

# Conversion from weird objects to normal lists
pixels = [list(row) for row in image[2]]
print(pixels)

Output with a 4 pixel square image with some black and orange :

[[13, 6, 2, 248, 124, 38], [246, 123, 38, 16, 8, 2]]

Where each sub-list is a row of pixels, with R, G, B, R, G, B, R ...

  • So the top left pixel has these RGB values : 13, 6, 2
  • The top right : 248, 124, 38
  • Bottom left : 246, 123, 38
  • Bottom right : 16, 8, 2

Upvotes: 1

Lars
Lars

Reputation: 158

Having read the docs I understand your confusion. I will refer to an answer made by Constantin, using the following code should do the job:

import png, array

point = (2, 10) # coordinates of pixel to be painted red

reader = png.Reader(filename='image.png')
w, h, pixels, metadata = reader.read_flat()
pixel_byte_width = 4 if metadata['alpha'] else 3
pixel_position = point[0] + point[1] * w
new_pixel_value = (255, 0, 0, 0) if metadata['alpha'] else (255, 0, 0)
pixels[
  pixel_position * pixel_byte_width :
  (pixel_position + 1) * pixel_byte_width] = array.array('B', new_pixel_value)

output = open('image-with-red-dot.png', 'wb')
writer = png.Writer(w, h, **metadata)
writer.write_array(output, pixels)
output.close()

Upvotes: 1

Related Questions