imgconv_nocgo.go

 1//go:build !cgo
 2
 3package clib
 4
 5import (
 6	"bytes"
 7	"image"
 8	"image/png"
 9
10	_ "image/gif"
11	_ "image/jpeg"
12)
13
14// DecodeToPNG takes raw image bytes (JPEG, PNG, BMP, GIF, etc.) and returns
15// PNG-encoded bytes along with image dimensions.
16// This is the pure Go fallback used when cgo is not available.
17func DecodeToPNG(data []byte) (ImageConvertResult, bool) {
18	if len(data) == 0 {
19		return ImageConvertResult{}, false
20	}
21
22	img, _, err := image.Decode(bytes.NewReader(data))
23	if err != nil {
24		return ImageConvertResult{}, false
25	}
26
27	var buf bytes.Buffer
28	if err := png.Encode(&buf, img); err != nil {
29		return ImageConvertResult{}, false
30	}
31
32	bounds := img.Bounds()
33	return ImageConvertResult{
34		PNGData: buf.Bytes(),
35		Width:   bounds.Dx(),
36		Height:  bounds.Dy(),
37	}, true
38}
39
40// ImageDimensions returns the width and height of an image without fully
41// decoding pixel data.
42// This is the pure Go fallback — it must fully decode the image since Go's
43// stdlib does not support header-only reads.
44func ImageDimensions(data []byte) (width, height int, ok bool) {
45	if len(data) == 0 {
46		return 0, 0, false
47	}
48
49	img, _, err := image.Decode(bytes.NewReader(data))
50	if err != nil {
51		return 0, 0, false
52	}
53
54	bounds := img.Bounds()
55	return bounds.Dx(), bounds.Dy(), true
56}