wkb.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """Load/dump geometries using the well-known binary (WKB) format.
  2. Also provides pickle-like convenience functions.
  3. """
  4. import shapely
  5. def loads(data, hex=False):
  6. """Load a geometry from a WKB byte string.
  7. If ``hex=True``, the string will be hex-encoded.
  8. Raises
  9. ------
  10. GEOSException, UnicodeDecodeError
  11. If ``data`` contains an invalid geometry.
  12. """
  13. return shapely.from_wkb(data)
  14. def load(fp, hex=False):
  15. """Load a geometry from an open file.
  16. Raises
  17. ------
  18. GEOSException, UnicodeDecodeError
  19. If the given file contains an invalid geometry.
  20. """
  21. data = fp.read()
  22. return loads(data, hex=hex)
  23. def dumps(ob, hex=False, srid=None, **kw):
  24. """Dump a WKB representation of a geometry to a byte string.
  25. If ``hex=True``, the string will be hex-encoded.
  26. Parameters
  27. ----------
  28. ob : geometry
  29. The geometry to export to well-known binary (WKB) representation.
  30. hex : bool
  31. If true, export the WKB as a hexadecimal string. The default is to
  32. return a binary string/bytes object.
  33. srid : int
  34. Spatial reference system ID to include in the output. The default value
  35. means no SRID is included.
  36. **kw : kwargs, optional
  37. Keyword output options passed to :func:`~shapely.to_wkb`.
  38. """
  39. if srid is not None:
  40. # clone the object and set the SRID before dumping
  41. ob = shapely.set_srid(ob, srid)
  42. kw["include_srid"] = True
  43. if "big_endian" in kw:
  44. # translate big_endian=True/False into byte_order=0/1
  45. # but if not specified, keep the default of byte_order=-1 (native)
  46. big_endian = kw.pop("big_endian")
  47. byte_order = 0 if big_endian else 1
  48. kw.update(byte_order=byte_order)
  49. return shapely.to_wkb(ob, hex=hex, **kw)
  50. def dump(ob, fp, hex=False, **kw):
  51. """Dump a geometry to an open file."""
  52. fp.write(dumps(ob, hex=hex, **kw))