Files
Reims-Go/internal/guesttools/dib.go
T

170 lines
4.9 KiB
Go

package guesttools
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
)
// pngMagic is the standard 8-byte PNG file signature.
var pngMagic = []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}
const maxClipboardImageDim = 16384
// IsPNG reports whether data starts with the PNG signature.
func IsPNG(data []byte) bool {
return len(data) >= len(pngMagic) && bytes.Equal(data[:len(pngMagic)], pngMagic)
}
// EncodeImageToDIB encodes an image into a standard 32-bit bottom-up Windows
// CF_DIB (BITMAPINFOHEADER + BGRA pixels) accepted by all Windows applications.
func EncodeImageToDIB(img image.Image) ([]byte, error) {
b := img.Bounds()
w, h := b.Dx(), b.Dy()
if w <= 0 || h <= 0 || w > maxClipboardImageDim || h > maxClipboardImageDim {
return nil, fmt.Errorf("invalid clipboard image dimensions %dx%d", w, h)
}
rgba := image.NewNRGBA(image.Rect(0, 0, w, h))
draw.Draw(rgba, rgba.Bounds(), img, b.Min, draw.Src)
const hdrSize = 40
pixelBytes := w * h * 4
out := make([]byte, hdrSize+pixelBytes)
binary.LittleEndian.PutUint32(out[0:4], hdrSize)
binary.LittleEndian.PutUint32(out[4:8], uint32(w))
binary.LittleEndian.PutUint32(out[8:12], uint32(h)) // positive => bottom-up
binary.LittleEndian.PutUint16(out[12:14], 1) // planes
binary.LittleEndian.PutUint16(out[14:16], 32) // bpp
binary.LittleEndian.PutUint32(out[16:20], 0) // BI_RGB
binary.LittleEndian.PutUint32(out[20:24], uint32(pixelBytes))
for y := 0; y < h; y++ {
srcY := h - 1 - y
srcRow := rgba.Pix[srcY*rgba.Stride:]
dstRow := out[hdrSize+y*w*4:]
for x := 0; x < w; x++ {
si := x * 4
di := x * 4
dstRow[di+0] = srcRow[si+2] // B
dstRow[di+1] = srcRow[si+1] // G
dstRow[di+2] = srcRow[si+0] // R
dstRow[di+3] = srcRow[si+3] // A
}
}
return out, nil
}
// EncodePNGToDIB decodes pngBytes and returns a Windows CF_DIB byte slice.
func EncodePNGToDIB(pngBytes []byte) ([]byte, error) {
if !IsPNG(pngBytes) {
return nil, errors.New("payload is not a valid PNG")
}
cfg, err := png.DecodeConfig(bytes.NewReader(pngBytes))
if err != nil {
return nil, fmt.Errorf("decode PNG config: %w", err)
}
if cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width > maxClipboardImageDim || cfg.Height > maxClipboardImageDim {
return nil, fmt.Errorf("PNG dimensions out of bounds: %dx%d", cfg.Width, cfg.Height)
}
img, err := png.Decode(bytes.NewReader(pngBytes))
if err != nil {
return nil, fmt.Errorf("decode PNG: %w", err)
}
return EncodeImageToDIB(img)
}
// DecodeDIBToPNG converts Windows CF_DIB bytes (24-bit or 32-bit BI_RGB / BI_BITFIELDS)
// into PNG bytes.
func DecodeDIBToPNG(dib []byte) ([]byte, error) {
if len(dib) < 40 {
return nil, errors.New("CF_DIB too short")
}
hdrSize := int(binary.LittleEndian.Uint32(dib[0:4]))
if hdrSize < 40 || hdrSize > len(dib) {
return nil, fmt.Errorf("unsupported DIB header size %d", hdrSize)
}
w := int(int32(binary.LittleEndian.Uint32(dib[4:8])))
rawH := int(int32(binary.LittleEndian.Uint32(dib[8:12])))
topDown := rawH < 0
h := rawH
if h < 0 {
h = -h
}
if w <= 0 || h <= 0 || w > maxClipboardImageDim || h > maxClipboardImageDim {
return nil, fmt.Errorf("invalid DIB dimensions %dx%d", w, h)
}
bpp := int(binary.LittleEndian.Uint16(dib[14:16]))
comp := binary.LittleEndian.Uint32(dib[16:20])
const (
biRGB = 0
biBitfields = 3
)
if comp != biRGB && comp != biBitfields {
return nil, fmt.Errorf("unsupported DIB compression %d", comp)
}
if bpp != 24 && bpp != 32 {
return nil, fmt.Errorf("unsupported DIB bit depth %d", bpp)
}
pixelOffset := hdrSize
if comp == biBitfields && hdrSize == 40 {
// Standard BITMAPINFOHEADER + BI_BITFIELDS appends 3 DWORD color masks (12 bytes).
pixelOffset += 12
}
if clrUsed := int(binary.LittleEndian.Uint32(dib[32:36])); clrUsed > 0 && bpp <= 8 {
pixelOffset += clrUsed * 4
}
rowStride := ((w*bpp + 31) / 32) * 4
if pixelOffset+rowStride*h > len(dib) {
return nil, errors.New("CF_DIB pixel data truncated")
}
img := image.NewNRGBA(image.Rect(0, 0, w, h))
// Track whether any 32-bit pixel carries non-zero alpha; many Windows apps
// leave the 4th byte of BI_RGB 32-bit DIBs as 0 (opaque XRGB).
hasAlpha := false
if bpp == 32 {
for y := 0; y < h && !hasAlpha; y++ {
row := dib[pixelOffset+y*rowStride:]
for x := 0; x < w; x++ {
if row[x*4+3] != 0 {
hasAlpha = true
break
}
}
}
}
for y := 0; y < h; y++ {
srcY := h - 1 - y
if topDown {
srcY = y
}
row := dib[pixelOffset+srcY*rowStride:]
for x := 0; x < w; x++ {
if bpp == 32 {
off := x * 4
a := row[off+3]
if !hasAlpha {
a = 255
}
img.SetNRGBA(x, y, color.NRGBA{R: row[off+2], G: row[off+1], B: row[off+0], A: a})
} else {
off := x * 3
img.SetNRGBA(x, y, color.NRGBA{R: row[off+2], G: row[off+1], B: row[off+0], A: 255})
}
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
return nil, fmt.Errorf("encode PNG: %w", err)
}
return buf.Bytes(), nil
}