or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

convenience.mdimage-container.mdindex.mdreading.mdwriting.md

reading.mddocs/

0

# PNG Reading Operations

1

2

Comprehensive PNG decoding capabilities with format conversion, chunk access, and metadata extraction. The Reader class supports all PNG color types and bit depths with automatic format detection and conversion options.

3

4

## Capabilities

5

6

### PNG File Reading

7

8

The Reader class provides the primary interface for reading PNG files from various sources including files, file objects, and byte data.

9

10

```python { .api }

11

class Reader:

12

def __init__(self, _guess=None, filename=None, file=None, bytes=None):

13

"""

14

Initialize PNG reader from file, file object, or bytes.

15

16

Parameters:

17

- filename: str, path to PNG file

18

- file: file-like object with PNG data

19

- bytes: bytes object containing PNG data

20

- _guess: deprecated, for internal use

21

"""

22

23

def read(self, lenient=False):

24

"""

25

Read PNG file and return image data.

26

27

Parameters:

28

- lenient: bool, whether to ignore some PNG specification violations

29

30

Returns:

31

tuple: (width, height, rows, info) where:

32

- width: int, image width in pixels

33

- height: int, image height in pixels

34

- rows: iterator of pixel rows

35

- info: dict with PNG metadata

36

"""

37

38

def read_flat(self):

39

"""

40

Read PNG into single flat array.

41

42

Returns:

43

tuple: (width, height, pixels, info) where pixels is 1D array

44

"""

45

```

46

47

### Format Conversion

48

49

Convert PNG data to specific color formats regardless of the original PNG color type.

50

51

```python { .api }

52

def asRGB(self):

53

"""

54

Convert image to RGB format (3 values per pixel).

55

56

Returns:

57

tuple: (width, height, rows, info) with RGB pixel data

58

"""

59

60

def asRGBA(self):

61

"""

62

Convert image to RGBA format (4 values per pixel).

63

64

Returns:

65

tuple: (width, height, rows, info) with RGBA pixel data

66

"""

67

68

def asRGB8(self):

69

"""

70

Convert to RGB with 8-bits per sample.

71

72

Returns:

73

tuple: (width, height, rows, info) with 8-bit RGB data

74

"""

75

76

def asRGBA8(self):

77

"""

78

Convert to RGBA with 8-bits per sample.

79

80

Returns:

81

tuple: (width, height, rows, info) with 8-bit RGBA data

82

"""

83

84

def asDirect(self):

85

"""

86

Return direct array representation without palette indirection.

87

88

Returns:

89

tuple: (width, height, rows, info) with direct color values

90

"""

91

```

92

93

### Palette Operations

94

95

Extract and manipulate color palettes from palette-based PNG images.

96

97

```python { .api }

98

def palette(self, alpha='natural'):

99

"""

100

Extract palette as RGB or RGBA tuples.

101

102

Parameters:

103

- alpha: str, how to handle alpha channel ('natural', 'force', 'remove')

104

105

Returns:

106

list: RGB 3-tuples or RGBA 4-tuples

107

"""

108

```

109

110

### Low-Level Chunk Access

111

112

Direct access to PNG chunks for advanced PNG manipulation and metadata extraction.

113

114

```python { .api }

115

def chunk(self, lenient=False):

116

"""

117

Read next PNG chunk.

118

119

Parameters:

120

- lenient: bool, whether to ignore specification violations

121

122

Returns:

123

tuple: (chunk_type, chunk_data) or None if no more chunks

124

"""

125

126

def chunks(self):

127

"""

128

Iterator over all PNG chunks.

129

130

Yields:

131

tuple: (chunk_type, chunk_data) for each chunk

132

"""

133

134

def preamble(self, lenient=False):

135

"""

136

Read PNG header and return image metadata.

137

138

Parameters:

139

- lenient: bool, whether to ignore specification violations

140

141

Returns:

142

dict: PNG header information (width, height, bit depth, etc.)

143

"""

144

```

145

146

## Usage Examples

147

148

### Basic PNG Reading

149

150

```python

151

import png

152

153

# Read from file

154

reader = png.Reader(filename='image.png')

155

width, height, rows, info = reader.read()

156

157

# Process pixel data

158

for row in rows:

159

# Each row is an array of pixel values

160

print(f"Row has {len(row)} values")

161

```

162

163

### Format Conversion

164

165

```python

166

import png

167

168

# Read PNG and convert to specific format

169

reader = png.Reader(filename='palette_image.png')

170

width, height, rows, info = reader.asRGBA()

171

172

# Now all pixels are RGBA regardless of original format

173

for row in rows:

174

# Each pixel has 4 values: R, G, B, A

175

pixels = list(row)

176

for i in range(0, len(pixels), 4):

177

r, g, b, a = pixels[i:i+4]

178

print(f"Pixel: R={r}, G={g}, B={b}, A={a}")

179

```

180

181

### Palette Extraction

182

183

```python

184

import png

185

186

# Extract palette from palette-based PNG

187

reader = png.Reader(filename='palette_image.png')

188

palette = reader.palette()

189

190

print(f"Palette has {len(palette)} colors:")

191

for i, color in enumerate(palette):

192

if len(color) == 3:

193

r, g, b = color

194

print(f"Color {i}: RGB({r}, {g}, {b})")

195

else:

196

r, g, b, a = color

197

print(f"Color {i}: RGBA({r}, {g}, {b}, {a})")

198

```

199

200

### Chunk Inspection

201

202

```python

203

import png

204

205

# Examine PNG chunks

206

reader = png.Reader(filename='image.png')

207

for chunk_type, chunk_data in reader.chunks():

208

print(f"Chunk: {chunk_type}, Size: {len(chunk_data)} bytes")

209

210

# Handle specific chunk types

211

if chunk_type == b'tEXt':

212

# Text chunk contains key-value metadata

213

text_data = chunk_data.decode('latin1')

214

print(f"Text: {text_data}")

215

elif chunk_type == b'gAMA':

216

# Gamma chunk

217

gamma = int.from_bytes(chunk_data, 'big') / 100000.0

218

print(f"Gamma: {gamma}")

219

```