English 中文(简体)
印刷PNG图像,制作成一个扫描网络打印机
原标题:Printing PNG images to a zebra network printer

我正试图找到一种将图像印制到一个冰箱并造成大量麻烦的方法。

The docs:

The first encoding, known as B64, encodes the data using the MIME Base64 scheme. Base64 is used to encode e-mail atachedments ...
Base64 encodes six bits to the byte, for an expantion of 33 percent over the un-enclosed data.
The second encoding, known as Z64, first compresses the data using the LZ77 algorithm to reduce its size. (This algorithm is used by the PKZIP and is intergral to the PNG graphics format.)
The compressed data is then encoded using the MIME Base64 scheme as described above.
A CRC will be calculated accross the Base64-encoded data.

但是,它没有很大的影响力。

基本上,我正试图遵守

private byte[] GetItemFromPath(string filepath)
{   
    using (MemoryStream ms = new MemoryStream())
    {
        using (Image img = Image.FromFile(filepath))
        {
            img.Save(ms, ImageFormat.Png);
            return ms.ToArray();
        }
    }
}

随后试图用类似东西印刷:

var initialArray = GetItemFromPath("C:\RED.png");
string converted = Convert.ToBase64String(b);

PrintThis(string.Format(@"~DYRED.PNG,P,P,{1},0,:B64:
{0}
^XA
^F0200,200^XGRED.PNG,1,1^FS
^XZ", converted .ToString(), initialArray.Length));

无论是B64还是Z64,都接受了这些物质。

I ve tried a few variations, and a couple of methods for generating the CRC and calculating the size . But none seem to work and the download of the graphics to the printer is always getting aborted.

是否有人设法完成这样的事情? 或者知道我会错了什么?

问题回答

来我回答的所有信贷来自:user Raydur。 他在LabView上找到了一种可以打开的拉比语解决方案,以便播下图像。 我个人拿着我的打印机,我刚刚用它来标出正确的图像代码,这样我就可以在我的代码中复制。 我所缺的一件大事是废除我的《 Hexa》。 例如,1A是罚款的,但如果你只是A,你需要先拨0A。 你寄出的ZPL的档案数量也是星体阵列的原始规模,而不是数据的最终显示。

我鼓励许多、许多论坛和斯夸多花招试图说明这一点,因为似乎这样简单。 我尝试了在其他地方张贴的每一种解决办法,但我真的希望只是印刷一个.PNG,因为我的印刷商手册(Mobile QLN320)支持它。 它说,要么将其送至基地64,要么是 Hexa,我试图两处都徒劳。 对于想要做基地64的人,我在一份旧的手册中发现,你需要人工计算所寄出的每个包裹的《儿童权利公约》编码,因此我选择了更方便的六dec路线。 因此,我在这里要工作!

        string ipAddress = "192.168.1.30";
        int port = 6101;

        string zplImageData = string.Empty;
        //Make sure no transparency exists. I had some trouble with this. This PNG has a white background
        string filePath = @"C:UsersPathToLogo.png";
        byte[] binaryData = System.IO.File.ReadAllBytes(filePath);
        foreach (Byte b in binaryData)
        {
            string hexRep = String.Format("{0:X}", b);
            if (hexRep.Length == 1)
                hexRep = "0" + hexRep;
            zplImageData += hexRep;
          }
          string zplToSend = "^XA" + "^MNN" + "^LL500" + "~DYE:LOGO,P,P," + binaryData.Length + ",," + zplImageData+"^XZ";
          string printImage = "^XA^FO115,50^IME:LOGO.PNG^FS^XZ";

        try
        {
            // Open connection
            System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
            client.Connect(ipAddress, port);

            // Write ZPL String to connection
            System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream(),Encoding.UTF8);
            writer.Write(zplToSend);
            writer.Flush();
            writer.Write(printImage);
            writer.Flush();
            // Close Connection
            writer.Close();
            client.Close();
        }
        catch (Exception ex)
        {
            // Catch Exception
        }

rel=“noretinger”>ZPL II Program Guide documents the ~>DG/code>的指令和GRF格式(第124页)下载图像:

首先,你们必须把图像转换为1bpp双层图像,然后将其转换成代为代号的星体。 你可以进一步压缩图像,以减少传播时间。 然后,你可以用<编码>^ID指令打印图像。

虽然在<代码>~DY的指挥中存在对PNG图像的内在支持,但记录不全,似乎对某些打印机模式不可行。 ZB64格式基本上没有记录,从Zebra支持获得更多信息的努力没有结果。 如果你在ZB64上打下了心脏,你可以使用 rel=“noreferer” 。 (look to ImagePrintDemo.java and com.zebra.sdk.printer.internal.GraphicsConversionUtilZpl.sendImage ToStream.

一旦掌握了指挥数据,如果打印机有一台打印机,也可通过TCP/IP发送,或者可以以书面形式向打印机发送。

The code below prints a 5 kB PNG as a 13 kB compressed GRF (60 kB uncompressed):

class Program
{
    static unsafe void Main(string[] args)
    {
        var baseStream = new MemoryStream();
        var tw = new StreamWriter(baseStream, Encoding.UTF8);

        using (var bmpSrc = new Bitmap(Image.FromFile(@"label.png")))
        {
            tw.WriteLine(ZplImage.GetGrfStoreCommand("R:LBLRA2.GRF", bmpSrc));
        }
        tw.WriteLine(ZplImage.GetGrfPrintCommand("R:LBLRA2.GRF"));
        tw.WriteLine(ZplImage.GetGrfDeleteCommand("R:LBLRA2.GRF"));

        tw.Flush();
        baseStream.Position = 0;

        var gdipj = new GdiPrintJob("ZEBRA S4M-200dpi ZPL", GdiPrintJobDataType.Raw, "Raw print", null);
        gdipj.WritePage(baseStream);
        gdipj.CompleteJob();
    }
}

class ZplImage
{
    public static string GetGrfStoreCommand(string filename, Bitmap bmpSource)
    {
        if (bmpSource == null)
        {
            throw new ArgumentNullException("bmpSource");
        }
        validateFilename(filename);

        var dim = new Rectangle(Point.Empty, bmpSource.Size);
        var stride = ((dim.Width + 7) / 8);
        var bytes = stride * dim.Height;

        using (var bmpCompressed = bmpSource.Clone(dim, PixelFormat.Format1bppIndexed))
        {
            var result = new StringBuilder();

            result.AppendFormat("^XA~DG{2},{0},{1},", stride * dim.Height, stride, filename);
            byte[][] imageData = GetImageData(dim, stride, bmpCompressed);

            byte[] previousRow = null;
            foreach (var row in imageData)
            {
                appendLine(row, previousRow, result);
                previousRow = row;
            }
            result.Append(@"^FS^XZ");

            return result.ToString();
        }
    }

    public static string GetGrfDeleteCommand(string filename)
    {
        validateFilename(filename);

        return string.Format("^XA^ID{0}^FS^XZ", filename);
    }

    public static string GetGrfPrintCommand(string filename)
    {
        validateFilename(filename);

        return string.Format("^XA^FO0,0^XG{0},1,1^FS^XZ", filename);
    }

    static Regex regexFilename = new Regex("^[REBA]:[A-Z0-9]{1,8}\.GRF$");

    private static void validateFilename(string filename)
    {
        if (!regexFilename.IsMatch(filename))
        {
            throw new ArgumentException("Filename must be in the format "
                + "R:XXXXXXXX.GRF.  Drives are R, E, B, A.  Filename can "
                + "be alphanumeric between 1 and 8 characters.", "filename");
        }
    }

    unsafe private static byte[][] GetImageData(Rectangle dim, int stride, Bitmap bmpCompressed)
    {
        byte[][] imageData;
        var data = bmpCompressed.LockBits(dim, ImageLockMode.ReadOnly, PixelFormat.Format1bppIndexed);
        try
        {
            byte* pixelData = (byte*)data.Scan0.ToPointer();
            byte rightMask = (byte)(0xff << (data.Stride * 8 - dim.Width));
            imageData = new byte[dim.Height][];

            for (int row = 0; row < dim.Height; row++)
            {
                byte* rowStart = pixelData + row * data.Stride;
                imageData[row] = new byte[stride];

                for (int col = 0; col < stride; col++)
                {
                    byte f = (byte)(0xff ^ rowStart[col]);
                    f = (col == stride - 1) ? (byte)(f & rightMask) : f;
                    imageData[row][col] = f;
                }
            }
        }
        finally
        {
            bmpCompressed.UnlockBits(data);
        }
        return imageData;
    }

    private static void appendLine(byte[] row, byte[] previousRow, StringBuilder baseStream)
    {
        if (row.All(r => r == 0))
        {
            baseStream.Append(",");
            return;
        }

        if (row.All(r => r == 0xff))
        {
            baseStream.Append("!");
            return;
        }

        if (previousRow != null && MatchByteArray(row, previousRow))
        {
            baseStream.Append(":");
            return;
        }

        byte[] nibbles = new byte[row.Length * 2];
        for (int i = 0; i < row.Length; i++)
        {
            nibbles[i * 2] = (byte)(row[i] >> 4);
            nibbles[i * 2 + 1] = (byte)(row[i] & 0x0f);
        }

        for (int i = 0; i < nibbles.Length; i++)
        {
            byte cPixel = nibbles[i];

            int repeatCount = 0;
            for (int j = i; j < nibbles.Length && repeatCount <= 400; j++)
            {
                if (cPixel == nibbles[j])
                {
                    repeatCount++;
                }
                else
                {
                    break;
                }
            }

            if (repeatCount > 2)
            {
                if (repeatCount == nibbles.Length - i
                    && (cPixel == 0 || cPixel == 0xf))
                {
                    if (cPixel == 0)
                    {
                        if (i % 2 == 1)
                        {
                            baseStream.Append("0");
                        }
                        baseStream.Append(",");
                        return;
                    }
                    else if (cPixel == 0xf)
                    {
                        if (i % 2 == 1)
                        {
                            baseStream.Append("F");
                        }
                        baseStream.Append("!");
                        return;
                    }
                }
                else
                {
                    baseStream.Append(getRepeatCode(repeatCount));
                    i += repeatCount - 1;
                }
            }
            baseStream.Append(cPixel.ToString("X"));
        }
    }

    private static string getRepeatCode(int repeatCount)
    {
        if (repeatCount > 419)
            throw new ArgumentOutOfRangeException();

        int high = repeatCount / 20;
        int low = repeatCount % 20;

        const string lowString = " GHIJKLMNOPQRSTUVWXY";
        const string highString = " ghijklmnopqrstuvwxyz";

        string repeatStr = "";
        if (high > 0)
        {
            repeatStr += highString[high];
        }
        if (low > 0)
        {
            repeatStr += lowString[low];
        }

        return repeatStr;
    }

    private static bool MatchByteArray(byte[] row, byte[] previousRow)
    {
        for (int i = 0; i < row.Length; i++)
        {
            if (row[i] != previousRow[i])
            {
                return false;
            }
        }

        return true;
    }
}

internal static class NativeMethods
{
    #region winspool.drv

    #region P/Invokes

    [DllImport("winspool.Drv", SetLastError = true, CharSet = CharSet.Unicode)]
    internal static extern bool OpenPrinter(string szPrinter, out IntPtr hPrinter, IntPtr pd);

    [DllImport("winspool.Drv", SetLastError = true, CharSet = CharSet.Unicode)]
    internal static extern bool ClosePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", SetLastError = true, CharSet = CharSet.Unicode)]
    internal static extern UInt32 StartDocPrinter(IntPtr hPrinter, Int32 level, IntPtr di);

    [DllImport("winspool.Drv", SetLastError = true, CharSet = CharSet.Unicode)]
    internal static extern bool EndDocPrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", SetLastError = true, CharSet = CharSet.Unicode)]
    internal static extern bool StartPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", SetLastError = true, CharSet = CharSet.Unicode)]
    internal static extern bool EndPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", SetLastError = true, CharSet = CharSet.Unicode)]
    internal static extern bool WritePrinter(
        // 0
        IntPtr hPrinter,
        [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pBytes,
        // 2
        UInt32 dwCount,
        out UInt32 dwWritten);

    #endregion

    #region Structs

    [StructLayout(LayoutKind.Sequential)]
    internal struct DOC_INFO_1
    {
        [MarshalAs(UnmanagedType.LPWStr)]
        public string DocName;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string OutputFile;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string Datatype;
    }

    #endregion

    #endregion
}

/// <summary>
/// Represents a print job in a spooler queue
/// </summary>
public class GdiPrintJob
{
    IntPtr PrinterHandle;
    IntPtr DocHandle;

    /// <summary>
    /// The ID assigned by the print spooler to identify the job
    /// </summary>
    public UInt32 PrintJobID { get; private set; }

    /// <summary>
    /// Create a print job with a enumerated datatype
    /// </summary>
    /// <param name="PrinterName"></param>
    /// <param name="dataType"></param>
    /// <param name="jobName"></param>
    /// <param name="outputFileName"></param>
    public GdiPrintJob(string PrinterName, GdiPrintJobDataType dataType, string jobName, string outputFileName)
        : this(PrinterName, translateType(dataType), jobName, outputFileName)
    {
    }

    /// <summary>
    /// Create a print job with a string datatype
    /// </summary>
    /// <param name="PrinterName"></param>
    /// <param name="dataType"></param>
    /// <param name="jobName"></param>
    /// <param name="outputFileName"></param>
    public GdiPrintJob(string PrinterName, string dataType, string jobName, string outputFileName)
    {
        if (string.IsNullOrWhiteSpace(PrinterName))
            throw new ArgumentNullException("PrinterName");
        if (string.IsNullOrWhiteSpace(dataType))
            throw new ArgumentNullException("PrinterName");

        IntPtr hPrinter;
        if (!NativeMethods.OpenPrinter(PrinterName, out hPrinter, IntPtr.Zero))
            throw new Win32Exception();
        this.PrinterHandle = hPrinter;

        NativeMethods.DOC_INFO_1 docInfo = new NativeMethods.DOC_INFO_1()
        {
            DocName = jobName,
            Datatype = dataType,
            OutputFile = outputFileName
        };
        IntPtr pDocInfo = Marshal.AllocHGlobal(Marshal.SizeOf(docInfo));
        RuntimeHelpers.PrepareConstrainedRegions();
        try
        {
            Marshal.StructureToPtr(docInfo, pDocInfo, false);
            UInt32 docid = NativeMethods.StartDocPrinter(hPrinter, 1, pDocInfo);
            if (docid == 0)
                throw new Win32Exception();
            this.PrintJobID = docid;
        }
        finally
        {
            Marshal.FreeHGlobal(pDocInfo);
        }
    }

    /// <summary>
    /// Write the data of a single page or a precomposed PCL document
    /// </summary>
    /// <param name="data"></param>
    public void WritePage(Stream data)
    {
        if (data == null)
            throw new ArgumentNullException("data");
        if (!data.CanRead && !data.CanWrite)
            throw new ObjectDisposedException("data");
        if (!data.CanRead)
            throw new NotSupportedException("stream is not readable");

        if (!NativeMethods.StartPagePrinter(this.PrinterHandle))
            throw new Win32Exception();

        byte[] buffer = new byte[0x14000]; /* 80k is Stream.CopyTo default */
        uint read = 1;
        while ((read = (uint)data.Read(buffer, 0, buffer.Length)) != 0)
        {
            UInt32 written;
            if (!NativeMethods.WritePrinter(this.PrinterHandle, buffer, read, out written))
                throw new Win32Exception();

            if (written != read)
                throw new InvalidOperationException("Error while writing to stream");
        }

        if (!NativeMethods.EndPagePrinter(this.PrinterHandle))
            throw new Win32Exception();
    }

    /// <summary>
    /// Complete the current job
    /// </summary>
    public void CompleteJob()
    {
        if (!NativeMethods.EndDocPrinter(this.PrinterHandle))
            throw new Win32Exception();
    }

    #region datatypes
    private readonly static string[] dataTypes = new string[] 
    { 
        // 0
        null, 
        "RAW", 
        // 2
        "RAW [FF appended]",
        "RAW [FF auto]",
        // 4
        "NT EMF 1.003", 
        "NT EMF 1.006",
        // 6
        "NT EMF 1.007", 
        "NT EMF 1.008", 
        // 8
        "TEXT", 
        "XPS_PASS", 
        // 10
        "XPS2GDI" 
    };

    private static string translateType(GdiPrintJobDataType type)
    {
        return dataTypes[(int)type];
    }
    #endregion
}

public enum GdiPrintJobDataType
{
    Unknown = 0,
    Raw = 1,
    RawAppendFF = 2,
    RawAuto = 3,
    NtEmf1003 = 4,
    NtEmf1006 = 5,
    NtEmf1007 = 6,
    NtEmf1008 = 7,
    Text = 8,
    XpsPass = 9,
    Xps2Gdi = 10
}

由于某种原因,我无法从B64获得工作,但幸运的是,我能够利用老大 Java的印本,把Z64(在3个灵魂研究日或那样)投入工作。

在其他地方,在ZPL方案拟定方面 • 《指南》:

"The value of the field is calculated the CRC-16 for the contents of a specified file using the CRC16-CCITT polynomial which is x^16 + x^12 + x^5 + 1. It is calculated using an initial CRC of 0x0000."

日本除外,现在可以检查。 Catalogue of parametrised CRC letters with 16 bits () and look for the XMODEM算法, 当时情况是:

width=16 poly=0x1021 init=0x0000 refin=false refout=false
xorout=0x0000 check=0x31c3 name="XMODEM"

Aha. 然后,我开始寻找我所需要的其余部分,并 following如下:

因此,我阅读了该档案,作为星号(Uint8Array),将它同LZ77混为一谈,将其改成星阵列,使用基64编码,当时,我计算了《儿童权利公约》,并将它推到我的ZPL ~DT指挥系统,节省约40%。 美丽。

不幸的是,我制定一种专有的解决办法,因此我不能张贴任何法典。

亲爱!

- 男子可以做些什么。

在阅读ZPL手册后,需要计算。 Cyclic Redundancy(CRC)用于图像。 http://web.archive.org/web/20120306081652/http://www.eagleairaust.com.au/code/crc16.htm

// Update the CRC for transmitted and received data using
// the CCITT 16bit algorithm (X^16 + X^12 + X^5 + 1).

unsigned char ser_data;
static unsigned int crc;

crc  = (unsigned char)(crc >> 8) | (crc << 8);
crc ^= ser_data;
crc ^= (unsigned char)(crc & 0xff) >> 4;
crc ^= (crc << 8) << 4;
crc ^= ((crc & 0xff) << 4) << 1;

You can also refer to Wikipedia s page on CRC, as it contains other code examples as well.

否则,你就会 good。 我将研究如何使用Zebra SDKs。 我知道安乐斯会向打印机发送图像,为你们节省。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签