You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
1.5 KiB

4 years ago
  1. #!/usr/bin/env python3
  2. #
  3. # RunLength decoder (Adobe version) implementation based on PDF Reference
  4. # version 1.4 section 3.3.4.
  5. #
  6. # * public domain *
  7. #
  8. import sys
  9. def rldecode(data):
  10. """
  11. RunLength decoder (Adobe version) implementation based on PDF Reference
  12. version 1.4 section 3.3.4:
  13. The RunLengthDecode filter decodes data that has been encoded in a
  14. simple byte-oriented format based on run length. The encoded data
  15. is a sequence of runs, where each run consists of a length byte
  16. followed by 1 to 128 bytes of data. If the length byte is in the
  17. range 0 to 127, the following length + 1 (1 to 128) bytes are
  18. copied literally during decompression. If length is in the range
  19. 129 to 255, the following single byte is to be copied 257 - length
  20. (2 to 128) times during decompression. A length value of 128
  21. denotes EOD.
  22. """
  23. decoded = []
  24. i=0
  25. while i < len(data):
  26. #print "data[%d]=:%d:" % (i,ord(data[i]))
  27. length = ord(data[i])
  28. if length == 128:
  29. break
  30. if length >= 0 and length < 128:
  31. run = data[i+1:(i+1)+(length+1)]
  32. #print "length=%d, run=%s" % (length+1,run)
  33. decoded.append(run)
  34. i = (i+1) + (length+1)
  35. if length > 128:
  36. run = data[i+1]*(257-length)
  37. #print "length=%d, run=%s" % (257-length,run)
  38. decoded.append(run)
  39. i = (i+1) + 1
  40. return ''.join(decoded)