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

            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;
        }

 

posted @ 2015-09-25 17:54  如.若  阅读(2057)  评论(0编辑  收藏  举报