首先我初始化打印机(ESC @):
addBytesCommand(Data(bytes: [0x1B, 0x40]))
然后我设置换行量(ESC 3 n):
addBytesCommand(Data(bytes: [0x1B, 0x33, 24]))
然后我正尝试使用(ESC *)命令来打印图像:
addBytesCommand(Data(bytes: [0x1B, 0x2A, 33]))
let image = #imageLiteral(resourceName: "icon_circle_remove_filled")
let imageWidth = image.size.width
let lowByte = UInt8(Int(imageWidth) & 0x00ff)
let highByte = UInt8((Int(imageWidth) & 0xff00) >> 8)
addBytesCommand(Data(bytes: [lowByte, highByte]))
我从此解释中使用的低字节和高字节逻辑:
ESC/POS Image Printing。
之后,我尝试使用此扩展的UIImage获取图像图像数据以发送到打印机。
extension UIImage {
func pixelData() -> [UInt8]? {
guard let cgImage = self.cgImage else { return nil }
let size = self.size
let bitsPerPixel = UInt8(cgImage.bitsPerPixel)
let bitsPerComponent = cgImage.bitsPerComponent
let bytesPerRow = cgImage.bytesPerRow
let dataSize = bytesPerRow * cgImage.height
var pixelData = [UInt8](repeating: 0, count: dataSize)
let colorSpace = CGColorSpaceCreateDeviceGray()
let context = CGContext(data: &pixelData,
width: Int(size.width),
height: Int(size.height),
bitsPerComponent: bitsPerComponent,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue)
context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
return pixelData
}
这就是我遇到的问题。我不知道pixelData
到底包含什么,如何将其转换为正确的数据类型?
获取打印位图信息的正确方法是什么?