joeylib2/tools/common/toolPng.h

51 lines
1.9 KiB
C

// Part of JoeyLib, Copyright (c) 2026 Scott Duensing, under the MIT License.
// See LICENSE.md for license information.
// SPDX-License-Identifier: MIT
//
// toolPng.h - PNG for the JoeyLib host tools: decode any PNG (every colour
// type and bit depth, Adam7, tRNS) to an indexed or RGBA image, and encode
// an indexed or RGBA image. Self-contained C99 over toolZlib.
#ifndef TOOL_PNG_H
#define TOOL_PNG_H
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#define TOOL_PNG_PALETTE_MAX 256u
#define TOOL_PNG_ERROR_BYTES 160u
// An image: indexed (a palette-colour PNG, one byte a pixel, palette entries
// RGBA with tRNS's alpha) or RGBA (four bytes a pixel, everything else,
// converted: grey spread to RGB, 16-bit samples cut to their high byte, a
// tRNS colour made transparent).
typedef struct ToolImageT {
uint32_t width;
uint32_t height;
bool indexed;
uint8_t *pixels;
uint16_t paletteCount;
uint8_t palette[TOOL_PNG_PALETTE_MAX][4];
} ToolImageT;
// A blank image (pixels zeroed, an empty palette); false when out of memory.
bool toolImageCreate(ToolImageT *img, uint32_t width, uint32_t height, bool indexed);
// Free an image's pixels (the struct is the caller's).
void toolImageFree(ToolImageT *img);
// An RGBA copy of src (indexed or not) into dst, which this creates.
bool toolImageToRgba(const ToolImageT *src, ToolImageT *dst);
// Decode a PNG from memory or a file. On failure the reason is in err.
bool toolPngDecode(const uint8_t *data, size_t len, ToolImageT *img, char err[TOOL_PNG_ERROR_BYTES]);
bool toolPngLoad(const char *path, ToolImageT *img, char err[TOOL_PNG_ERROR_BYTES]);
// Encode an image as PNG into a malloc'd buffer, or write it to a file:
// indexed as colour type 3 (8-bit, a tRNS when any entry is not opaque),
// RGBA as colour type 6.
bool toolPngEncode(const ToolImageT *img, uint8_t **out, size_t *outLen);
bool toolPngSave(const char *path, const ToolImageT *img);
#endif