package escpos import ( "fmt" "image" "image/color" ) // rasterBandHeight is the number of rows sent per GS v 0 command. Splitting // tall images keeps every command within the height limits of all supported // models (TM-T20 accepts up to 2303 rows). const rasterBandHeight = 256 // maxRasterWidthBytes bounds the image width so xL/xH stay meaningful. const maxRasterWidthBytes = 0xFFFF // RasterImage appends img as one or more GS v 0 raster bit images. Pixels // darker than 50% luminance, after compositing onto white paper, print black. // Dither images first (see the raster package) for photographic content. The // width is padded with white up to a multiple of 8 dots. func (b *Builder) RasterImage(img image.Image) error { bounds := img.Bounds() width, height := bounds.Dx(), bounds.Dy() if width <= 0 || height <= 0 { return fmt.Errorf("%w: image is empty", ErrInvalidArgument) } widthBytes := (width + 7) / 8 if widthBytes > maxRasterWidthBytes { return fmt.Errorf("%w: image is %d dots wide", ErrInvalidArgument, width) } dark := darkFunc(img) row := make([]byte, widthBytes) for top := 0; top < height; top += rasterBandHeight { rows := min(rasterBandHeight, height-top) b.buf.Write([]byte{gs, 'v', '0', 0, byte(widthBytes), byte(widthBytes >> 8), byte(rows), byte(rows >> 8)}) for y := top; y < top+rows; y++ { clear(row) for x := range width { if dark(bounds.Min.X+x, bounds.Min.Y+y) { row[x/8] |= 0x80 >> (x % 8) } } b.buf.Write(row) } } return nil } // darkFunc returns a pixel test for img, with fast paths for the image types // the raster package produces. func darkFunc(img image.Image) func(x, y int) bool { switch m := img.(type) { case *image.Paletted: dark := make([]bool, len(m.Palette)) for i, c := range m.Palette { dark[i] = isDark(c) } return func(x, y int) bool { idx := m.ColorIndexAt(x, y) return int(idx) < len(dark) && dark[idx] } case *image.Gray: return func(x, y int) bool { return m.GrayAt(x, y).Y < 0x80 } } return func(x, y int) bool { return isDark(img.At(x, y)) } } // isDark composites c onto white and reports whether its luminance is below // 50%. RGBA returns alpha-premultiplied values, so adding the uncovered // fraction of white is enough to composite. func isDark(c color.Color) bool { r, g, bl, a := c.RGBA() white := 0xFFFF - a luma := (299*(r+white) + 587*(g+white) + 114*(bl+white)) / 1000 return luma < 0x8000 }