base.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. class BaseImage(object):
  2. """
  3. Base QRCode image output class.
  4. """
  5. kind = None
  6. allowed_kinds = None
  7. def __init__(self, border, width, box_size, *args, **kwargs):
  8. self.border = border
  9. self.width = width
  10. self.box_size = box_size
  11. self.pixel_size = (self.width + self.border*2) * self.box_size
  12. self._img = self.new_image(**kwargs)
  13. def drawrect(self, row, col):
  14. """
  15. Draw a single rectangle of the QR code.
  16. """
  17. raise NotImplementedError("BaseImage.drawrect")
  18. def save(self, stream, kind=None):
  19. """
  20. Save the image file.
  21. """
  22. raise NotImplementedError("BaseImage.save")
  23. def pixel_box(self, row, col):
  24. """
  25. A helper method for pixel-based image generators that specifies the
  26. four pixel coordinates for a single rect.
  27. """
  28. x = (col + self.border) * self.box_size
  29. y = (row + self.border) * self.box_size
  30. return [(x, y), (x + self.box_size - 1, y + self.box_size - 1)]
  31. def new_image(self, **kwargs): # pragma: no cover
  32. """
  33. Build the image class. Subclasses should return the class created.
  34. """
  35. return None
  36. def get_image(self, **kwargs):
  37. """
  38. Return the image class for further processing.
  39. """
  40. return self._img
  41. def check_kind(self, kind, transform=None):
  42. """
  43. Get the image type.
  44. """
  45. if kind is None:
  46. kind = self.kind
  47. allowed = not self.allowed_kinds or kind in self.allowed_kinds
  48. if transform:
  49. kind = transform(kind)
  50. if not allowed:
  51. allowed = kind in self.allowed_kinds
  52. if not allowed:
  53. raise ValueError(
  54. "Cannot set %s type to %s" % (type(self).__name__, kind))
  55. return kind