2

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?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Shiatryx
  • 31
  • 2

1 Answers1

1

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()
Lars
  • 128
  • 2
  • 8