提问人:A K 提问时间:11/13/2023 最后编辑:A K 更新时间:11/18/2023 访问量:62
在纯PHP的esc / pos打印机上直接打印
Direct printing on esc/pos printers in pure PHP
问:
几年来,我一直在使用这个库进行直接打印。最近,我需要以纯形式编写代码。所以我写了以下代码:
<?php
// Printer IP and Port
$printerIp = '192.168.10.177';
$printerPort = 9100;
// Connect to the printer
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "Error: socket_create failed\n";
}
$connect = socket_connect($socket, $printerIp, $printerPort);
if ($connect === false) {
echo "Error: socket_connect failed\n";
}
// ESC/POS command to initialize the printer
$initializeCommand = "\x1B\x40"; // ESC @
// Send the initialization command
socket_write($socket, $initializeCommand, strlen($initializeCommand));
// Load your image
$imagePath = '../Reception/images/abc.jpg';
$image = imagecreatefromjpeg($imagePath);
// Get image dimensions
$width = imagesx($image);
$height = imagesy($image);
// Convert image to binary data
$binaryData = '';
for ($y = 0; $y < $height; $y++) {
$slice = '';
for ($x = 0; $x < $width; $x++) {
$color = imagecolorat($image, $x, $y);
$greyness = (int)((($color >> 16) & 0xFF) * 0.3 + (($color >> 8) & 0xFF) * 0.59 + ($color & 0xFF) * 0.11) >> 7;
$dot = (1 - $greyness);
$slice .= chr($dot);
}
$binaryData .= $slice;
}
// Close the image resource
imagedestroy($image);
// ESC/POS command for Raster bit image
$rasterCommand = "\x1D\x76\x30\x00"; // GS v 0 0
// Send the image data
socket_write($socket, $rasterCommand, strlen($rasterCommand));
socket_write($socket, pack('v', $width), 2); // Send the width
socket_write($socket, pack('v', $height), 2); // Send the height
socket_write($socket, $binaryData, strlen($binaryData));
// ESC/POS feed
$partialFeedCommand = "\x1B\x64\x0A"; // GS d n
// Send the partial cut command
socket_write($socket, $partialFeedCommand, strlen($partialFeedCommand));
// ESC/POS command for partial cut
$partialCutCommand = "\x1D\x56\x01"; // GS V 1
// Send the partial cut command
socket_write($socket, $partialCutCommand, strlen($partialCutCommand));
// Close the socket
socket_close($socket);
?>
打印的不是连续的,行与行之间会留出空格:请看我打印的图像
您有什么解决方案? 谢谢
我使用过 ESC/POS 命令手册指南和这个库
更新
我以这种方式计算了 xL、xH、yL、yH 参数,但照片输出仍然没有区别:
// Calculate xL, xH, yL, yH parameters
$xL = $width % 256;
$xH = floor($width / 256);
$yL = $height % 256;
$yH = floor($height / 256);
// Send xL, xH, yL, yH parameters to the printer
socket_write($socket, $rasterCommand, strlen($rasterCommand));
socket_write($socket, pack('C', $xL), 1); // Send xL
socket_write($socket, pack('C', $xH), 1); // Send xH
socket_write($socket, pack('C', $yL), 1); // Send yL
socket_write($socket, pack('C', $yH), 1); // Send yH
socket_write($socket, $binaryData, strlen($binaryData));
答: 暂无答案
评论
ASCII GS v 0 m xL xH yL yH
str_repeat("\0", $imgHeight * $imgWidth)
if($bit == 8)
for($bit = 0;$bit<8;$bit++)
1000