热敏打印机打印图片

来源:互联网 发布:河南大学 双一流 知乎 编辑:程序博客网 时间:2024/06/11 05:22

热敏打印机打印图片

最近做了一款打印机的app。其他撇开不说,我们来谈一谈如何打印图片。


  • 打印机指令如图所示
    打印机指令
最初不明白这个指令到底说的什么意思,不过想到最后,突然开窍了,然后试了一试,图片数据解析出来,兴奋的跑了一下打印机。结果,还是打印不出东西。当时我就再想,按理说,不应该出错。最后的最后,由同事大神(mrdaios)同事提醒了一下(有可能是打印机的缓冲区一次性写入不了那么多字节,导致打印失败)。立马换成循环往打印机写入字节,结果打印出来了。

思路展现

  • 1.先获到取图片像素,代码如下,其中inputPixels是存储的是像素信息。
 // 1.获得图片的像素 以及上下文    UInt32 *inputPixels;    CGImageRef inputCGImage = [image CGImage];    size_t w = CGImageGetWidth(inputCGImage);    size_t h = CGImageGetHeight(inputCGImage);    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();    //每个像素的字节数    NSInteger bytesPerPixel = 4;    //每个组成像素的 位深    NSInteger bitsPerComponent = 8;    //每行字节数    NSInteger bitmapBytesPerRow = w * bytesPerPixel;    //通过calloc开辟一段连续的内存空间    inputPixels = (UInt32 *)calloc(w * h, sizeof(UInt32));    //获取图像数据    CGContextRef context =        CGBitmapContextCreate(inputPixels, w, h, bitsPerComponent, bitmapBytesPerRow, colorSpace,              kCGImageAlphaPremultipliedLast |kCGBitmapByteOrder32Big);
  • 2.根据像素颜色值,解析成打印机能够识别的二进制流。因为打印机指令是每个像素打印一个点(0或者1)。所以有两种实现方法(1是把每个像素判断成0 1代码,存入数组,再每次取出8位<一个字节8位>,通过幂运算算出这个字节等于多少。2是通过位运算算出字节等于多少。),以下是位运算的代码片段:
  //输出的图片    NSInteger outWidth = w / 8;    if (w % 8 != 0)    {        ++outWidth;    }    Byte *outPixels = (Byte *)calloc(outWidth * h, sizeof(Byte));    memset(outPixels, 0xff, outWidth * h);    // 2.操作像素    for (NSInteger i = 0; i < h; i++)    {        for (NSInteger j = 0; j < w; j++)        {            Byte *outPixel = outPixels + (outWidth * i) + j / 8;            UInt32 *currentPixel = inputPixels + (w * i) + j;            UInt32 color = *currentPixel;            //在打印区间和不透明            if (!((R(color) > 0xEF && G(color) > 0xEF && B(color) > 0xEF)) && A(color) != 0)            {                *outPixel &= ~(1 << (7 - j % 8));            }        }    }    bitData = [NSData dataWithBytes:outPixels length:outWidth * h];

最后,不然忘记释放哦。

    // 3 释放    CGColorSpaceRelease(colorSpace);    CGContextRelease(context);    free(inputPixels);    free(outPixels);

写在最后:

这是我第一次写博客,也是第一次弄硬件产品,爬过很多坑,如有bug,请见谅。。。

2 0