or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-drawing.mdaudio-sound.mdcore-system.mddrawing-shapes.mdevent-input.mdgame-objects.mdgraphics-display.mdindex.mdinput-devices.mdjoystick-gamepad.mdmath-utils.mdsurface-image.mdtext-font.mdtime-animation.mdtransform-image.md

surface-image.mddocs/

0

# Surface and Image Operations

1

2

Surface creation, manipulation, and image loading/saving. Surfaces are pygame's fundamental building blocks for graphics - they represent images in memory that can be drawn on, transformed, and blitted to other surfaces.

3

4

## Capabilities

5

6

### Surface Creation

7

8

Create surfaces for drawing and image manipulation.

9

10

```python { .api }

11

class Surface:

12

def __init__(self, size: tuple[int, int], flags: int = 0, depth: int = 0, masks = None):

13

"""

14

Create a new Surface object representing an image.

15

16

Args:

17

size (tuple[int, int]): (width, height) in pixels

18

flags (int): Special surface properties

19

depth (int): Color depth in bits per pixel

20

masks: Color bit masks for advanced surface creation

21

"""

22

23

def Surface(size: tuple[int, int], flags: int = 0, depth: int = 0, masks = None) -> pygame.Surface:

24

"""Create a new Surface - functional interface."""

25

```

26

27

### Surface Drawing Operations

28

29

Core methods for drawing on surfaces and combining them.

30

31

```python { .api }

32

def blit(self, source: pygame.Surface, dest: tuple[int, int], area: pygame.Rect = None, special_flags: int = 0) -> pygame.Rect:

33

"""

34

Draw one surface onto another.

35

36

Args:

37

source (pygame.Surface): Surface to draw

38

dest (tuple[int, int]): (x, y) position to draw at

39

area (pygame.Rect, optional): Portion of source to draw

40

special_flags (int): Blending flags

41

42

Returns:

43

pygame.Rect: Area that was affected

44

"""

45

46

def blits(self, blit_sequence: list, doreturn: int = 1) -> list[pygame.Rect]:

47

"""

48

Draw many surfaces onto this surface.

49

50

Args:

51

blit_sequence (list): List of (source, dest) or (source, dest, area) tuples

52

doreturn (int): Whether to return list of affected rectangles

53

54

Returns:

55

list[pygame.Rect]: List of affected areas if doreturn=1

56

"""

57

58

def fill(self, color, rect: pygame.Rect = None, special_flags: int = 0) -> pygame.Rect:

59

"""

60

Fill surface with a solid color.

61

62

Args:

63

color: Color to fill with

64

rect (pygame.Rect, optional): Area to fill (None for entire surface)

65

special_flags (int): Blending flags

66

67

Returns:

68

pygame.Rect: Area that was filled

69

"""

70

```

71

72

### Surface Conversion and Copying

73

74

Convert surfaces between pixel formats and create copies.

75

76

```python { .api }

77

def convert(self, surface: pygame.Surface = None) -> pygame.Surface:

78

"""

79

Convert surface to same pixel format as display for faster blitting.

80

81

Args:

82

surface (pygame.Surface, optional): Surface to match format with

83

84

Returns:

85

pygame.Surface: New surface with converted format

86

"""

87

88

def convert_alpha(self, surface: pygame.Surface = None) -> pygame.Surface:

89

"""

90

Convert surface to same pixel format as display with alpha channel.

91

92

Args:

93

surface (pygame.Surface, optional): Surface to match format with

94

95

Returns:

96

pygame.Surface: New surface with converted format and alpha

97

"""

98

99

def copy(self) -> pygame.Surface:

100

"""

101

Create an identical copy of the surface.

102

103

Returns:

104

pygame.Surface: New surface that is an exact copy

105

"""

106

```

107

108

### Pixel Access

109

110

Direct pixel manipulation for advanced graphics operations.

111

112

```python { .api }

113

def get_at(self, pos: tuple[int, int]) -> pygame.Color:

114

"""

115

Get color of a single pixel.

116

117

Args:

118

pos (tuple[int, int]): (x, y) pixel position

119

120

Returns:

121

pygame.Color: Color at the specified position

122

"""

123

124

def get_at_mapped(self, pos: tuple[int, int]) -> int:

125

"""

126

Get mapped pixel value at position.

127

128

Args:

129

pos (tuple[int, int]): (x, y) pixel position

130

131

Returns:

132

int: Mapped pixel value

133

"""

134

135

def set_at(self, pos: tuple[int, int], color) -> None:

136

"""

137

Set color of a single pixel.

138

139

Args:

140

pos (tuple[int, int]): (x, y) pixel position

141

color: Color to set

142

"""

143

144

def get_rect(self, **kwargs) -> pygame.Rect:

145

"""

146

Get rectangular area of the surface.

147

148

Args:

149

**kwargs: Keyword arguments to position the rectangle

150

151

Returns:

152

pygame.Rect: Rectangle representing surface area

153

"""

154

```

155

156

### Surface Properties

157

158

Access surface dimensions, format, and properties.

159

160

```python { .api }

161

def get_size(self) -> tuple[int, int]:

162

"""Get (width, height) of surface."""

163

164

def get_width(self) -> int:

165

"""Get width of surface in pixels."""

166

167

def get_height(self) -> int:

168

"""Get height of surface in pixels."""

169

170

def get_flags(self) -> int:

171

"""Get surface flags."""

172

173

def get_bitsize(self) -> int:

174

"""Get bits per pixel."""

175

176

def get_bytesize(self) -> int:

177

"""Get bytes per pixel."""

178

179

def get_masks(self) -> tuple[int, int, int, int]:

180

"""Get RGBA bit masks."""

181

182

def get_shifts(self) -> tuple[int, int, int, int]:

183

"""Get RGBA bit shifts."""

184

185

def get_losses(self) -> tuple[int, int, int, int]:

186

"""Get RGBA precision losses."""

187

188

def get_pitch(self) -> int:

189

"""Get bytes per row."""

190

191

def map_rgb(self, color) -> int:

192

"""

193

Map RGB color to pixel value for this surface's format.

194

195

Args:

196

color: Color to map

197

198

Returns:

199

int: Mapped pixel value

200

"""

201

202

def unmap_rgb(self, mapped_int: int) -> pygame.Color:

203

"""

204

Unmap pixel value to RGB color for this surface's format.

205

206

Args:

207

mapped_int (int): Mapped pixel value

208

209

Returns:

210

pygame.Color: RGB color

211

"""

212

213

def set_masks(self, masks: tuple[int, int, int, int]) -> None:

214

"""

215

Set RGBA bit masks for this surface.

216

217

Args:

218

masks (tuple[int, int, int, int]): (R, G, B, A) bit masks

219

"""

220

221

def set_shifts(self, shifts: tuple[int, int, int, int]) -> None:

222

"""

223

Set RGBA bit shifts for this surface.

224

225

Args:

226

shifts (tuple[int, int, int, int]): (R, G, B, A) bit shifts

227

"""

228

```

229

230

### Transparency and Color Key

231

232

Control surface transparency and color key effects.

233

234

```python { .api }

235

def set_alpha(self, alpha: int, flags: int = 0) -> None:

236

"""

237

Set alpha transparency for the surface.

238

239

Args:

240

alpha (int): Transparency value (0-255, 0=transparent, 255=opaque)

241

flags (int): Alpha blending flags

242

"""

243

244

def get_alpha(self) -> int:

245

"""

246

Get current alpha transparency value.

247

248

Returns:

249

int: Alpha value (0-255) or None if per-pixel alpha

250

"""

251

252

def set_colorkey(self, color, flags: int = 0) -> None:

253

"""

254

Set transparent color key.

255

256

Args:

257

color: Color to make transparent (None to unset)

258

flags (int): Colorkey flags

259

"""

260

261

def get_colorkey(self) -> pygame.Color:

262

"""

263

Get current colorkey.

264

265

Returns:

266

pygame.Color: Current colorkey color or None

267

"""

268

269

def get_palette(self) -> list[pygame.Color]:

270

"""

271

Get color palette for indexed color surfaces.

272

273

Returns:

274

list[pygame.Color]: List of colors in palette or None if not palette surface

275

"""

276

277

def get_palette_at(self, index: int) -> pygame.Color:

278

"""

279

Get single palette color by index.

280

281

Args:

282

index (int): Palette index

283

284

Returns:

285

pygame.Color: Color at specified palette index

286

"""

287

288

def set_palette(self, palette: list) -> None:

289

"""

290

Set color palette for indexed color surface.

291

292

Args:

293

palette (list): List of colors for palette

294

"""

295

296

def set_palette_at(self, index: int, color) -> None:

297

"""

298

Set single palette color by index.

299

300

Args:

301

index (int): Palette index

302

color: Color to set at index

303

"""

304

```

305

306

### Surface Clipping

307

308

Control the drawable area of a surface.

309

310

```python { .api }

311

def set_clip(self, rect: pygame.Rect = None) -> None:

312

"""

313

Set clipping area for drawing operations.

314

315

Args:

316

rect (pygame.Rect, optional): Clipping rectangle (None to reset)

317

"""

318

319

def get_clip(self) -> pygame.Rect:

320

"""

321

Get current clipping area.

322

323

Returns:

324

pygame.Rect: Current clipping rectangle

325

"""

326

```

327

328

### Surface Locking

329

330

Lock surface for direct pixel access.

331

332

```python { .api }

333

def lock(self) -> None:

334

"""Lock surface for pixel access (required for some operations)."""

335

336

def unlock(self) -> None:

337

"""Unlock surface after pixel access."""

338

339

def mustlock(self) -> bool:

340

"""

341

Check if surface must be locked for pixel access.

342

343

Returns:

344

bool: True if locking is required

345

"""

346

347

def get_locked(self) -> bool:

348

"""

349

Check if surface is currently locked.

350

351

Returns:

352

bool: True if surface is locked

353

"""

354

355

def get_locks(self) -> tuple:

356

"""

357

Get information about current surface locks.

358

359

Returns:

360

tuple: Lock information

361

"""

362

```

363

364

### Advanced Surface Operations

365

366

Advanced surface manipulation including subsurfaces and buffer access.

367

368

```python { .api }

369

def subsurface(self, rect: pygame.Rect) -> pygame.Surface:

370

"""

371

Create a subsurface that shares pixel data with parent.

372

373

Args:

374

rect (pygame.Rect): Area of parent surface to reference

375

376

Returns:

377

pygame.Surface: New subsurface

378

"""

379

380

def get_parent(self) -> pygame.Surface:

381

"""Get parent surface of a subsurface."""

382

383

def get_abs_parent(self) -> pygame.Surface:

384

"""Get absolute parent surface."""

385

386

def get_offset(self) -> tuple[int, int]:

387

"""Get offset of subsurface within parent."""

388

389

def get_abs_offset(self) -> tuple[int, int]:

390

"""Get absolute offset within top-level parent."""

391

392

def scroll(self, dx: int = 0, dy: int = 0) -> None:

393

"""

394

Shift surface image by dx, dy pixels.

395

396

Args:

397

dx (int): Horizontal shift

398

dy (int): Vertical shift

399

"""

400

401

def get_view(self, kind: str = '2') -> pygame.BufferProxy:

402

"""

403

Get array interface view of surface pixels.

404

405

Args:

406

kind (str): View type ('0', '1', '2', '3', or 'r', 'g', 'b', 'a')

407

408

Returns:

409

pygame.BufferProxy: Array interface to pixel data

410

"""

411

412

def get_buffer(self) -> pygame.BufferProxy:

413

"""

414

Get buffer object for surface.

415

416

Returns:

417

pygame.BufferProxy: Buffer interface to surface data

418

"""

419

420

def get_bounding_rect(self, min_alpha: int = 1) -> pygame.Rect:

421

"""

422

Get smallest rectangle containing non-transparent pixels.

423

424

Args:

425

min_alpha (int): Minimum alpha value to consider non-transparent

426

427

Returns:

428

pygame.Rect: Bounding rectangle of visible pixels

429

"""

430

431

def premul_alpha(self) -> pygame.Surface:

432

"""

433

Return copy with premultiplied alpha values.

434

435

Returns:

436

pygame.Surface: New surface with premultiplied alpha

437

"""

438

```

439

440

## Image Loading and Saving

441

442

Functions for loading and saving images from/to files.

443

444

```python { .api }

445

def load(file, namehint: str = "") -> pygame.Surface:

446

"""

447

Load an image from file or file-like object.

448

449

Args:

450

file: File path, file object, or file-like object

451

namehint (str): Hint about file format

452

453

Returns:

454

pygame.Surface: New surface with loaded image

455

"""

456

457

def save(surface: pygame.Surface, file, namehint: str = "") -> None:

458

"""

459

Save surface as an image file.

460

461

Args:

462

surface (pygame.Surface): Surface to save

463

file: File path or file object to save to

464

namehint (str): Hint about desired file format

465

"""

466

467

def get_extended() -> bool:

468

"""

469

Check if extended image formats are supported.

470

471

Returns:

472

bool: True if extended formats available

473

"""

474

475

def get_sdl_image_version() -> tuple[int, int, int]:

476

"""

477

Get SDL_image library version.

478

479

Returns:

480

tuple[int, int, int]: (major, minor, patch) version

481

"""

482

```

483

484

## Usage Examples

485

486

### Basic Surface Operations

487

488

```python

489

import pygame

490

491

pygame.init()

492

493

# Create surfaces

494

screen = pygame.display.set_mode((800, 600))

495

surface = pygame.Surface((100, 100))

496

497

# Fill surface with color

498

surface.fill((255, 0, 0)) # Red

499

500

# Draw surface onto screen

501

screen.blit(surface, (50, 50))

502

503

# Get surface properties

504

width, height = surface.get_size()

505

print(f"Surface size: {width}x{height}")

506

507

pygame.display.flip()

508

```

509

510

### Image Loading and Manipulation

511

512

```python

513

import pygame

514

515

pygame.init()

516

screen = pygame.display.set_mode((800, 600))

517

518

# Load image

519

try:

520

image = pygame.image.load("player.png")

521

# Convert for better performance

522

image = image.convert_alpha()

523

except pygame.error as e:

524

print(f"Could not load image: {e}")

525

# Create fallback surface

526

image = pygame.Surface((50, 50))

527

image.fill((0, 255, 0))

528

529

# Get image rectangle for positioning

530

image_rect = image.get_rect()

531

image_rect.center = (400, 300)

532

533

# Draw image

534

screen.blit(image, image_rect)

535

pygame.display.flip()

536

537

# Save screenshot

538

pygame.image.save(screen, "screenshot.png")

539

```

540

541

### Transparency and Alpha

542

543

```python

544

import pygame

545

546

pygame.init()

547

screen = pygame.display.set_mode((800, 600))

548

549

# Create surface with alpha channel

550

alpha_surface = pygame.Surface((100, 100), pygame.SRCALPHA)

551

alpha_surface.fill((255, 0, 0, 128)) # Semi-transparent red

552

553

# Create surface with colorkey transparency

554

colorkey_surface = pygame.Surface((100, 100))

555

colorkey_surface.fill((255, 0, 255)) # Magenta background

556

colorkey_surface.set_colorkey((255, 0, 255)) # Make magenta transparent

557

558

# Draw a shape that won't be transparent

559

pygame.draw.circle(colorkey_surface, (0, 255, 0), (50, 50), 30)

560

561

# Blit both surfaces

562

screen.fill((255, 255, 255))

563

screen.blit(alpha_surface, (100, 100))

564

screen.blit(colorkey_surface, (300, 100))

565

566

pygame.display.flip()

567

```

568

569

### Pixel Manipulation

570

571

```python

572

import pygame

573

574

pygame.init()

575

screen = pygame.display.set_mode((800, 600))

576

577

# Create surface for pixel manipulation

578

pixel_surface = pygame.Surface((200, 200))

579

pixel_surface.fill((0, 0, 0))

580

581

# Set individual pixels

582

for x in range(0, 200, 2):

583

for y in range(0, 200, 2):

584

color_value = ((x + y) * 255) // 400

585

pixel_surface.set_at((x, y), (color_value, 0, 255 - color_value))

586

587

# Read pixel color

588

center_color = pixel_surface.get_at((100, 100))

589

print(f"Center pixel color: {center_color}")

590

591

# Draw to screen

592

screen.blit(pixel_surface, (300, 200))

593

pygame.display.flip()

594

```

595

596

### Surface Clipping and Subsurfaces

597

598

```python

599

import pygame

600

601

pygame.init()

602

screen = pygame.display.set_mode((800, 600))

603

604

# Create a large surface

605

large_surface = pygame.Surface((300, 300))

606

large_surface.fill((100, 100, 100))

607

608

# Draw pattern on large surface

609

for i in range(0, 300, 20):

610

pygame.draw.line(large_surface, (255, 255, 0), (0, i), (300, i), 2)

611

612

# Create subsurface (shares pixel data with parent)

613

sub_surface = large_surface.subsurface(pygame.Rect(50, 50, 200, 200))

614

615

# Draw on subsurface (affects parent too)

616

pygame.draw.circle(sub_surface, (255, 0, 0), (100, 100), 50)

617

618

# Use clipping to restrict drawing area

619

large_surface.set_clip(pygame.Rect(0, 0, 150, 150))

620

pygame.draw.rect(large_surface, (0, 255, 0), (0, 0, 300, 300), 5) # Only draws in clipped area

621

622

# Draw to screen

623

screen.blit(large_surface, (200, 100))

624

pygame.display.flip()

625

```