morsemake.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python3.9
  2. # You'll need to change a few obvious things.
  3. # Amateur Radio and Amateur Programmer!
  4. # Chris Baird <cjb@brushtail.apana.org.au> did this January 2022
  5. import sys
  6. from PIL import Image, ImageDraw, ImageFont
  7. imagesize = (320,256)
  8. colourspace = "YCbCr" # the content has the greyscale channel all to itself
  9. yskip = 4
  10. ditlen = 2 # size of dits in pixels
  11. (margintop, marginleft, marginright, marginbot) = (8,12,imagesize[0]-12,imagesize[1]-8)
  12. y = margintop
  13. charcount = 0
  14. charsize = imagesize[0] // 8
  15. fnt = ImageFont.truetype("/usr/home/cjb/.fonts/microgramma.ttf", charsize)
  16. morsetable = \
  17. ( 128, 174, 74, 128, 19, 128, 68, 122, 180, 182, 128, 84,
  18. 206, 134, 86, 148, 252, 124, 60, 28, 12, 4, 132, 196,
  19. 228, 244, 226, 170, 128, 140, 128, 50, 106, 96, 136, 168,
  20. 144, 64, 40, 208, 8, 32, 120, 176, 72, 224, 160, 240,
  21. 104, 216, 80, 16, 192, 48, 24, 112, 104, 184, 200)
  22. def morse2string (c):
  23. global charcount
  24. s = ""
  25. c = ord(c) - 32
  26. if c > 64 and c < 91: c -= 32
  27. if c >= 0 and c < 59:
  28. charcount += 1
  29. b = morsetable[c]
  30. if b == 128: s += " "*2
  31. while (b & 255) != 128:
  32. if (b & 128): s += "... "
  33. else: s += ". "
  34. b <<= 1
  35. s += " "*2
  36. return s
  37. def drawditline (cwstring):
  38. global y
  39. x = (imagesize[0] - ditlen*len(cwstring)) // 2
  40. for i in range(len(cwstring)):
  41. if cwstring[i] == '.': c = 0
  42. else: c = 255
  43. for j in range(ditlen):
  44. p = im.getpixel ((x,y))
  45. im.putpixel ((x,y), (c, p[1], p[2]))
  46. x += 1
  47. y += yskip
  48. im = Image.new(mode=colourspace, size=imagesize, color=(255,128,128))
  49. d = ImageDraw.Draw (im)
  50. d.text((charsize*1.25,charsize*0.5), "VK2CJB", font=fnt, fill=(128,255,255))
  51. d.text((charsize*1.5,charsize*2), "MORSE", font=fnt, fill=(128,128,255))
  52. d.text((charsize*0.75,charsize*3), "CONTENT", font=fnt, fill=(128,255,128))
  53. ss=""
  54. while y < marginbot:
  55. c = sys.stdin.read(1)
  56. if c == '': break
  57. s = morse2string (c)
  58. if len(s)+len(ss) >= (marginright-marginleft)//ditlen:
  59. drawditline(ss)
  60. ss = ""
  61. ss += s
  62. drawditline(ss)
  63. imrgb = im.convert("RGB")
  64. imrgb.save("morseencoded.png")
  65. print ("Character count =", charcount)