def topil(self): """Returns a PIL.Image version of this Pix""" from PIL import Image # pylint: disable=import-outside-toplevel # Leptonica manages data in words, so it implicitly does an endian # swap. Tell Pillow about this when it reads the data. pix = self if sys.byteorder == 'little': if self.mode == 'RGB': raw_mode = 'XBGR' elif self.mode == 'RGBA': raw_mode = 'ABGR' elif self.mode == '1': raw_mode = '1;I' pix = Pix(lept.pixEndianByteSwapNew(pix._cdata)) else: raw_mode = self.mode pix = Pix(lept.pixEndianByteSwapNew(pix._cdata)) else: raw_mode = self.mode # no endian swap needed size = (pix._cdata.w, pix._cdata.h) bytecount = pix._cdata.wpl * 4 * pix._cdata.h buf = ffi.buffer(pix._cdata.data, bytecount) stride = pix._cdata.wpl * 4 im = Image.frombytes(self.mode, size, buf, 'raw', raw_mode, stride) return im
def _repr_png_(self): """iPython display hook returns png version of image """ data = ffi.new('l_uint8 **') size = ffi.new('size_t *') err = lept.pixWriteMemPng(data, size, self._cdata, 0) if err != 0: raise LeptonicaIOError("pixWriteMemPng") char_data = ffi.cast('char *', data[0]) return ffi.buffer(char_data, size[0])[:]
def __getstate__(self): data = ffi.new('l_uint32 **') size = ffi.new('size_t *') err = lept.pixSerializeToMemory(self._cdata, data, size) if err != 0: raise LeptonicaIOError("pixSerializeToMemory") char_data = ffi.cast('char *', data[0]) # Copy from C bytes to python bytes() data_bytes = ffi.buffer(char_data, size[0])[:] # Can now free C bytes lept.lept_free(char_data) return dict(data=data_bytes)
def write_implied_format(self, path, jpeg_quality=0, jpeg_progressive=0): """Write pix to the filename, with the extension indicating format. jpeg_quality -- quality (iff JPEG; 1 - 100, 0 for default) jpeg_progressive -- (iff JPEG; 0 for baseline seq., 1 for progressive) """ lept_format = lept.getImpliedFileFormat(os.fsencode(path)) with open(path, 'wb') as py_file: data = ffi.new('l_uint8 **pdata') size = ffi.new('size_t *psize') with _LeptonicaErrorTrap(): if lept_format == lept.L_JPEG_ENCODE: lept.pixWriteMemJpeg(data, size, self._cdata, jpeg_quality, jpeg_progressive) else: lept.pixWriteMem(data, size, self._cdata, lept_format) buffer = ffi.buffer(data[0], size[0]) py_file.write(buffer)
def get_palette_pdf_string(self): "Returns palette pre-formatted for use in PDF" buflen = len('< ') + len(' rrggbb') * self._cdata.ncolors + len('>') buf = ffi.buffer(self._cdata.cmapdatahex, buflen) return bytes(buf)
def read(self): buf = ffi.buffer(self._cdata.datacomp, self._cdata.nbytescomp) return bytes(buf)