229 lines
6.6 KiB
Go
229 lines
6.6 KiB
Go
package guesttools
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/binary"
|
|
"errors"
|
|
"fmt"
|
|
"image"
|
|
"image/color"
|
|
"image/draw"
|
|
"image/png"
|
|
"math/bits"
|
|
)
|
|
|
|
// 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)
|
|
}
|
|
|
|
// TrimPNG returns the portion of raw through the end of its IEND chunk.
|
|
func TrimPNG(raw []byte) ([]byte, bool) {
|
|
if !IsPNG(raw) {
|
|
return nil, false
|
|
}
|
|
for off := len(pngMagic); len(raw)-off >= 12; {
|
|
chunk := raw[off:]
|
|
size := binary.BigEndian.Uint32(chunk[:4])
|
|
if size > 0x7fffffff || uint64(size) > uint64(len(chunk)-12) {
|
|
return nil, false
|
|
}
|
|
off += int(size) + 12
|
|
if string(chunk[4:8]) == "IEND" {
|
|
if size != 0 {
|
|
return nil, false
|
|
}
|
|
return raw[:off], true
|
|
}
|
|
}
|
|
return nil, false
|
|
}
|
|
|
|
// 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 24/32-bit BI_RGB or 16/32-bit BI_BITFIELDS to PNG.
|
|
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 != 32 && !(comp == biRGB && bpp == 24) && !(comp == biBitfields && bpp == 16) {
|
|
return nil, fmt.Errorf("unsupported DIB bit depth %d", bpp)
|
|
}
|
|
|
|
pixelOffset := hdrSize
|
|
var masks [4]uint32
|
|
var shifts [4]int
|
|
var maxima [4]uint64
|
|
if comp == biBitfields {
|
|
switch {
|
|
case hdrSize == 40 && len(dib) >= 52:
|
|
pixelOffset += 12
|
|
case hdrSize >= 56:
|
|
masks[3] = binary.LittleEndian.Uint32(dib[52:56])
|
|
default:
|
|
return nil, errors.New("CF_DIB color masks truncated")
|
|
}
|
|
used := uint32(0)
|
|
for i := range masks {
|
|
if i < 3 {
|
|
masks[i] = binary.LittleEndian.Uint32(dib[40+i*4:])
|
|
} else if masks[i] == 0 {
|
|
continue
|
|
}
|
|
shifts[i] = bits.TrailingZeros32(masks[i])
|
|
field := masks[i] >> shifts[i]
|
|
if field == 0 || field&(field+1) != 0 || masks[i]&used != 0 || bits.Len32(masks[i]) > bpp {
|
|
return nil, errors.New("invalid CF_DIB color masks")
|
|
}
|
|
used |= masks[i]
|
|
maxima[i] = uint64(field)
|
|
}
|
|
}
|
|
tableBytes := uint64(binary.LittleEndian.Uint32(dib[32:36])) * 4
|
|
rowStride := ((w*bpp + 31) / 32) * 4
|
|
if uint64(pixelOffset)+tableBytes+uint64(rowStride)*uint64(h) > uint64(len(dib)) {
|
|
return nil, errors.New("CF_DIB pixel data truncated")
|
|
}
|
|
pixelOffset += int(tableBytes)
|
|
|
|
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 comp == biRGB && 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 comp == biBitfields {
|
|
pixel := row[x*(bpp/8):]
|
|
value := uint32(binary.LittleEndian.Uint16(pixel))
|
|
if bpp == 32 {
|
|
value = binary.LittleEndian.Uint32(pixel)
|
|
}
|
|
channels := [4]uint8{0, 0, 0, 255}
|
|
for i, mask := range masks {
|
|
if mask != 0 {
|
|
level := uint64((value & mask) >> shifts[i])
|
|
channels[i] = uint8((level*255 + maxima[i]/2) / maxima[i])
|
|
}
|
|
}
|
|
img.SetNRGBA(x, y, color.NRGBA{R: channels[0], G: channels[1], B: channels[2], A: channels[3]})
|
|
} else 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
|
|
}
|