无损 JBIG2 编码库(Lossless JBIG2 Encoder)

有网友希望提供 PDFPatcher 的 JBIG2 编码库,因发此博文。

此处提供的编码库源自agl在Github的开源代码。该代码编译后输出 EXE 文件,编码现存位图文件或 StdIn 提供的数据,未提供被其它应用程序调用的 DLL 库。为了在 PDF 补丁丁中增加 JBIG2 编码功能,我修改了该代码,去除了其有损压缩功能及 Leptonica 图像库的依赖关系,减少了编码器的文件大小。

导出函数

DLL 库导出的函数有三个(除下列方法之外,还有原代码提供的jbig2_encode_generic方法,该方法的调用方式请参见原代码的说明):

uint8_t *
jbig2_encode (int width, int height, int stride, bool zeroIsWhite, uint8_t * const bw, int *const length);

void release (uint8_t * const memblock);

jbig2_encode 方法用于编码传入的字节数组。其参数有六个:

  1. Width:图像宽度
  2. Height:图像高度
  3. Stride:一行像素所占的双字(DWORD)数
  4. ZeroIsWhite:将BW的0视为白色
  5. BW:图像的字节数组(Byte[]),此字节数组是原始黑白图像的二进制数据,默认情况下,二进制位1表示白色,0表示黑色
  6. Length:字节数组长度
  7. 传出参数:编码后的 JBIG2 字节数组

jbig2_encode 方法实际上是调用  jbig2_encode_generic方法,为方便从其它程序调用而设,见所附源代码。

release 方法用于释放 jbig2_encode 方法编码后字节数组所占用的内存,传入参数是 jbig2_encode 方法返回的指针。

C# 的调用方法

调用 JBIG2Encoder 类的 Encode 方法即可,该方法的传入参数为一位图:

///<summary>JBIG2 Lossless Encoder Wrapper</summary>
public static class JBig2Encoder
{
static uint White = 0x00FFFFFF;

public static byte[] Encode (Bitmap bmp, bool zeroIsWhite) {
var bits = bmp.LockBits (new System.Drawing.Rectangle (0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format1bppIndexed);
var bytes = Encode (bmp.Width, bmp.Height, bits.Stride, zeroIsWhite, bits.Scan0);
bmp.UnlockBits (bits);
return bytes;
}

private static byte[] Encode (int width, int height, int stride, bool zeroIsWhite, IntPtr b) {
int l = 0;
var r = NativeMethods.jbig2_encode (width, height, stride, zeroIsWhite, b, ref l);
byte[] result = new byte[l];
Marshal.Copy (r, result, 0, l);
NativeMethods.release (r);
return result;
}

class NativeMethods
{
[DllImport ("jbig2enc.dll")]
internal static extern IntPtr jbig2_encode (int width, int height, int stride, bool zeroIsWhite, IntPtr data, ref int length);

[DllImport ("jbig2enc.dll")]
internal static extern IntPtr release (IntPtr data);
}
}

下载(Download)

点击此处下载 JBIG2 无损压缩 DLL 库

Click here to download JBIG2 Lossless Compression DLL.

原文地址:https://www.cnblogs.com/pdfpatcher/p/2334231.html