How to generate a dynamic GRF image to ZPL ZEBRA print

lucasrhuan picture lucasrhuan · Dec 27, 2012 · Viewed 20.5k times · Source

I have a problem.

I´m generating a dynamic BMP image and trying to send this to a ZEBRA printer by ZPL commands. I need to convert my BMP to a GRF image. I think that my Hexadecimal extracted by the BMP image isn´t correct.

The printed image is blurred and incorrect.

This is my code:

string bitmapFilePath = @oldArquivo;  // file is attached to this support article
byte[] bitmapFileData = System.IO.File.ReadAllBytes(bitmapFilePath);
int fileSize = bitmapFileData.Length;

Bitmap ImgTemp = new Bitmap(bitmapFilePath);
Size ImgSize = ImgTemp.Size;
ImgTemp.Dispose();

// The following is known about test.bmp.  It is up to the developer
// to determine this information for bitmaps besides the given test.bmp.            
int width = ImgSize.Width;
int height = ImgSize.Height;
int bitmapDataOffset = 62; // 62 = header of the image
int bitmapDataLength = fileSize - 62;// 8160;    

double widthInBytes = Math.Ceiling(width / 8.0);    

// Copy over the actual bitmap data from the bitmap file.
// This represents the bitmap data without the header information.
byte[] bitmap = new byte[bitmapDataLength];
Buffer.BlockCopy(bitmapFileData, bitmapDataOffset, bitmap, 0, (bitmapDataLength));

// Invert bitmap colors
for (int i = 0; i < bitmapDataLength; i++)
{
    bitmap[i] ^= 0xFF;
}

// Create ASCII ZPL string of hexadecimal bitmap data
string ZPLImageDataString = BitConverter.ToString(bitmap).Replace("-", string.Empty);

string comandoCompleto = "~DG" + nomeImagem + ".GRF,0" + bitmapDataLength.ToString() + ",0" + widthInBytes.ToString() + "," + ZPLImageDataString;

Answer

Jigsore picture Jigsore · Dec 28, 2012

Try the following code. Not tested!

public static string CreateGRF(string filename, string imagename)
{
    Bitmap bmp = null;
    BitmapData imgData = null;
    byte[] pixels;
    int x, y, width;
    StringBuilder sb;
    IntPtr ptr;

    try
    {
        bmp = new Bitmap(filename);
        imgData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format1bppIndexed);
        width = (bmp.Width + 7) / 8;
        pixels = new byte[width];
        sb = new StringBuilder(width * bmp.Height * 2);
        ptr = imgData.Scan0;
        for (y = 0; y < bmp.Height; y++)
        {
            Marshal.Copy(ptr, pixels, 0, width);
            for (x = 0; x < width; x++)
                sb.AppendFormat("{0:X2}", (byte)~pixels[x]);
            ptr = (IntPtr)(ptr.ToInt64() + imgData.Stride);
        }
    }
    finally
    {
        if (bmp != null)
        {
            if (imgData != null) bmp.UnlockBits(imgData);
            bmp.Dispose();
        }
    }
    return String.Format("~DG{0}.GRF,{1},{2},", imagename, width * y, width) + sb.ToString();
}