C# 热敏打印机 Socket 网络链接 打印 图片 (二)

本文介绍了如何使用C#编程语言,通过网络连接将图片发送到小票打印机,并详细解释了如何实现图片转换为可打印格式的过程。
            IPAddress ip = IPAddress.Parse("192.168.1.212");
            IPEndPoint iport = new IPEndPoint(ip, 9100);//9100为小票打印机指定端口
            Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            soc.Connect(iport);
            bitmap = new Bitmap(@"D:\300X200.bmp");
            soc.Send(bmpToByte(bitmap));
            soc.Close();
        public static byte[] bmpToByte(Bitmap bmp)
        {
            int h = bmp.Height / 24 + 1;
            int w = bmp.Width;
            byte[][] all = new byte[2 + 2 * h + h * w][];

            all[0] = new byte[] { 0x1B, 0x33, 0x00 };

            Color pixelColor;
            // ESC * m nL nH 点阵图  
            byte[] escBmp = new byte[] { 0x1B, 0x2A, 0x21, (byte)(w % 256), (byte)(w / 256) };

            // 每行进行打印  
            for (int i = 0; i < h; i++)
            {
                all[i * (w + 2) + 1] = escBmp;
                for (int j = 0; j < w; j++)
                {
                    byte[] data = new byte[] { 0x00, 0x00, 0x00 };
                    for (int k = 0; k < 24; k++)
                    {
                        if (((i * 24) + k) < bmp.Height)
                        {
                            pixelColor = bmp.GetPixel(j, (i * 24) + k);
                            if (pixelColor.R == 0)
                            {
                                data[k / 8] += (byte)(128 >> (k % 8));
                            }
                        }
                    }
                    all[i * (w + 2) + j + 2] = data;
                }
                //换行  
                all[(i + 1) * (w + 2)] = PrinterCmdUtils.nextLine(1);
            }
            all[h * (w + 2) + 1] = PrinterCmdUtils.nextLine(2);

            return byteMerger(all);
        }
        public static byte[] byteMerger(byte[][] byteList)
        {
            int Length = 0;
            for (int i = 0; i < byteList.Length; i++)
            {
                Length += byteList[i].Length;
            }
            byte[] result = new byte[Length];

            int index = 0;
            for (int i = 0; i < byteList.Length; i++)
            {
                byte[] nowByte = byteList[i];
                for (int k = 0; k < byteList[i].Length; k++)
                {
                    result[index] = nowByte[k];
                    index++;
                }
            }
            return result;
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值