C# 热敏打印机 Socket 网络链接 打印 图片 (二)
1 IPAddress ip = IPAddress.Parse("192.168.1.212"); 2 IPEndPoint iport = new IPEndPoint(ip, 9100);//9100为小票打印机指定端口 3 Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 4 soc.Connect(iport); 5 bitmap = new Bitmap(@"D:\300X200.bmp"); 6 soc.Send(bmpToByte(bitmap)); 7 soc.Close();
1 public static byte[] bmpToByte(Bitmap bmp) 2 { 3 int h = bmp.Height / 24 + 1; 4 int w = bmp.Width; 5 byte[][] all = new byte[2 + 2 * h + h * w][]; 6 7 all[0] = new byte[] { 0x1B, 0x33, 0x00 }; 8 9 Color pixelColor; 10 // ESC * m nL nH 点阵图 11 byte[] escBmp = new byte[] { 0x1B, 0x2A, 0x21, (byte)(w % 256), (byte)(w / 256) }; 12 13 // 每行进行打印 14 for (int i = 0; i < h; i++) 15 { 16 all[i * (w + 2) + 1] = escBmp; 17 for (int j = 0; j < w; j++) 18 { 19 byte[] data = new byte[] { 0x00, 0x00, 0x00 }; 20 for (int k = 0; k < 24; k++) 21 { 22 if (((i * 24) + k) < bmp.Height) 23 { 24 pixelColor = bmp.GetPixel(j, (i * 24) + k); 25 if (pixelColor.R == 0) 26 { 27 data[k / 8] += (byte)(128 >> (k % 8)); 28 } 29 } 30 } 31 all[i * (w + 2) + j + 2] = data; 32 } 33 //换行 34 all[(i + 1) * (w + 2)] = PrinterCmdUtils.nextLine(1); 35 } 36 all[h * (w + 2) + 1] = PrinterCmdUtils.nextLine(2); 37 38 return byteMerger(all); 39 }
1 public static byte[] byteMerger(byte[][] byteList) 2 { 3 int Length = 0; 4 for (int i = 0; i < byteList.Length; i++) 5 { 6 Length += byteList[i].Length; 7 } 8 byte[] result = new byte[Length]; 9 10 int index = 0; 11 for (int i = 0; i < byteList.Length; i++) 12 { 13 byte[] nowByte = byteList[i]; 14 for (int k = 0; k < byteList[i].Length; k++) 15 { 16 result[index] = nowByte[k]; 17 index++; 18 } 19 } 20 return result; 21 }