images2swf.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. # Copyright (C) 2012, Almar Klein
  2. #
  3. # This code is subject to the (new) BSD license:
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are met:
  7. # * Redistributions of source code must retain the above copyright
  8. # notice, this list of conditions and the following disclaimer.
  9. # * Redistributions in binary form must reproduce the above copyright
  10. # notice, this list of conditions and the following disclaimer in the
  11. # documentation and/or other materials provided with the distribution.
  12. # * Neither the name of the <organization> nor the
  13. # names of its contributors may be used to endorse or promote products
  14. # derived from this software without specific prior written permission.
  15. #
  16. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  19. # ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  20. # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. """ Module images2swf
  27. Provides a function (writeSwf) to store a series of PIL images or numpy
  28. arrays in an SWF movie, that can be played on a wide range of OS's.
  29. This module came into being because I wanted to store a series of images
  30. in a movie that can be viewed by other people, and which I can embed in
  31. flash presentations. For writing AVI or MPEG you really need a c/c++
  32. library, and although the filesize is then very small, the quality is
  33. sometimes not adequate. Besides I'd like to be independent of yet another
  34. package. I tried writing animated gif using PIL (which is widely available),
  35. but the quality is so poor because it only allows for 256 different colors.
  36. [EDIT: thanks to Ant1, now the quality of animated gif isn't so bad!]
  37. I also looked into MNG and APNG, two standards similar to the PNG stanard.
  38. Both standards promise exactly what I need. However, hardly any application
  39. can read those formats, and I cannot import them in flash.
  40. Therefore I decided to check out the swf file format, which is very well
  41. documented. This is the result: a pure python module to create an SWF file
  42. that shows a series of images. The images are stored using the DEFLATE
  43. algorithm (same as PNG and ZIP and which is included in the standard Python
  44. distribution). As this compression algorithm is much more effective than
  45. that used in GIF images, we obtain better quality (24 bit colors + alpha
  46. channel) while still producesing smaller files (a test showed ~75%).
  47. Although SWF also allows for JPEG compression, doing so would probably
  48. require a third party library (because encoding JPEG is much harder).
  49. This module requires Python 2.x and numpy.
  50. sources and tools:
  51. - SWF on wikipedia
  52. - Adobes "SWF File Format Specification" version 10
  53. (http://www.adobe.com/devnet/swf/pdf/swf_file_format_spec_v10.pdf)
  54. - swftools (swfdump in specific) for debugging
  55. - iwisoft swf2avi can be used to convert swf to avi/mpg/flv with really
  56. good quality, while file size is reduced with factors 20-100.
  57. A good program in my opinion. The free version has the limitation
  58. of a watermark in the upper left corner.
  59. """
  60. import os
  61. import sys
  62. import zlib
  63. try:
  64. import numpy as np
  65. except ImportError:
  66. np = None
  67. try:
  68. import PIL.Image
  69. except ImportError:
  70. PIL = None
  71. # True if we are running on Python 3.
  72. # Code taken from six.py by Benjamin Peterson (MIT licensed)
  73. PY3 = sys.version_info[0] == 3
  74. string_types = (str,)
  75. integer_types = (int,)
  76. class_types = (type,)
  77. text_type = str
  78. binary_type = bytes
  79. # todo: use imageio/FreeImage to support reading JPEG images from SWF?
  80. def checkImages(images):
  81. """checkImages(images)
  82. Check numpy images and correct intensity range etc.
  83. The same for all movie formats.
  84. """
  85. # Init results
  86. images2 = []
  87. for im in images:
  88. if PIL and isinstance(im, PIL.Image.Image):
  89. # We assume PIL images are allright
  90. images2.append(im)
  91. elif np and isinstance(im, np.ndarray):
  92. # Check and convert dtype
  93. if im.dtype == np.uint8:
  94. images2.append(im) # Ok
  95. elif im.dtype in [np.float32, np.float64]:
  96. theMax = im.max()
  97. if theMax > 128 and theMax < 300:
  98. pass # assume 0:255
  99. else:
  100. im = im.copy()
  101. im[im < 0] = 0
  102. im[im > 1] = 1
  103. im *= 255
  104. images2.append(im.astype(np.uint8))
  105. else:
  106. im = im.astype(np.uint8)
  107. images2.append(im)
  108. # Check size
  109. if im.ndim == 2:
  110. pass # ok
  111. elif im.ndim == 3:
  112. if im.shape[2] not in [3, 4]:
  113. raise ValueError("This array can not represent an image.")
  114. else:
  115. raise ValueError("This array can not represent an image.")
  116. else:
  117. raise ValueError("Invalid image type: " + str(type(im)))
  118. # Done
  119. return images2
  120. # Base functions and classes
  121. class BitArray:
  122. """Dynamic array of bits that automatically resizes
  123. with factors of two.
  124. Append bits using .Append() or +=
  125. You can reverse bits using .Reverse()
  126. """
  127. def __init__(self, initvalue=None):
  128. self.data = np.zeros((16,), dtype=np.uint8)
  129. self._len = 0
  130. if initvalue is not None:
  131. self.Append(initvalue)
  132. def __len__(self):
  133. return self._len # self.data.shape[0]
  134. def __repr__(self):
  135. return self.data[: self._len].tobytes()
  136. def _checkSize(self):
  137. # check length... grow if necessary
  138. arraylen = self.data.shape[0]
  139. if self._len >= arraylen:
  140. tmp = np.zeros((arraylen * 2,), dtype=np.uint8)
  141. tmp[: self._len] = self.data[: self._len]
  142. self.data = tmp
  143. def __add__(self, value):
  144. self.Append(value)
  145. return self
  146. def Append(self, bits):
  147. # check input
  148. if isinstance(bits, BitArray):
  149. bits = str(bits)
  150. if isinstance(bits, int):
  151. bits = str(bits)
  152. if not isinstance(bits, string_types):
  153. raise ValueError("Append bits as strings or integers!")
  154. # add bits
  155. for bit in bits:
  156. self.data[self._len] = ord(bit)
  157. self._len += 1
  158. self._checkSize()
  159. def Reverse(self):
  160. """In-place reverse."""
  161. tmp = self.data[: self._len].copy()
  162. self.data[: self._len] = np.flipud(tmp)
  163. def ToBytes(self):
  164. """Convert to bytes. If necessary,
  165. zeros are padded to the end (right side).
  166. """
  167. bits = str(self)
  168. # determine number of bytes
  169. nbytes = 0
  170. while nbytes * 8 < len(bits):
  171. nbytes += 1
  172. # pad
  173. bits = bits.ljust(nbytes * 8, "0")
  174. # go from bits to bytes
  175. bb = binary_type()
  176. for i in range(nbytes):
  177. tmp = int(bits[i * 8 : (i + 1) * 8], 2)
  178. bb += intToUint8(tmp)
  179. # done
  180. return bb
  181. def intToUint32(i):
  182. return int(i).to_bytes(4, "little")
  183. def intToUint16(i):
  184. return int(i).to_bytes(2, "little")
  185. def intToUint8(i):
  186. return int(i).to_bytes(1, "little")
  187. def intToBits(i, n=None):
  188. """convert int to a string of bits (0's and 1's in a string),
  189. pad to n elements. Convert back using int(ss,2)."""
  190. ii = i
  191. # make bits
  192. bb = BitArray()
  193. while ii > 0:
  194. bb += str(ii % 2)
  195. ii = ii >> 1
  196. bb.Reverse()
  197. # justify
  198. if n is not None:
  199. if len(bb) > n:
  200. raise ValueError("intToBits fail: len larger than padlength.")
  201. bb = str(bb).rjust(n, "0")
  202. # done
  203. return BitArray(bb)
  204. def bitsToInt(bb, n=8):
  205. # Init
  206. value = ""
  207. # Get value in bits
  208. for i in range(len(bb)):
  209. b = bb[i : i + 1]
  210. tmp = bin(ord(b))[2:]
  211. # value += tmp.rjust(8,'0')
  212. value = tmp.rjust(8, "0") + value
  213. # Make decimal
  214. return int(value[:n], 2)
  215. def getTypeAndLen(bb):
  216. """bb should be 6 bytes at least
  217. Return (type, length, length_of_full_tag)
  218. """
  219. # Init
  220. value = ""
  221. # Get first 16 bits
  222. for i in range(2):
  223. b = bb[i : i + 1]
  224. tmp = bin(ord(b))[2:]
  225. # value += tmp.rjust(8,'0')
  226. value = tmp.rjust(8, "0") + value
  227. # Get type and length
  228. type = int(value[:10], 2)
  229. L = int(value[10:], 2)
  230. L2 = L + 2
  231. # Long tag header?
  232. if L == 63: # '111111'
  233. value = ""
  234. for i in range(2, 6):
  235. b = bb[i : i + 1] # becomes a single-byte bytes() on both PY3 and PY2
  236. tmp = bin(ord(b))[2:]
  237. # value += tmp.rjust(8,'0')
  238. value = tmp.rjust(8, "0") + value
  239. L = int(value, 2)
  240. L2 = L + 6
  241. # Done
  242. return type, L, L2
  243. def signedIntToBits(i, n=None):
  244. """convert signed int to a string of bits (0's and 1's in a string),
  245. pad to n elements. Negative numbers are stored in 2's complement bit
  246. patterns, thus positive numbers always start with a 0.
  247. """
  248. # negative number?
  249. ii = i
  250. if i < 0:
  251. # A negative number, -n, is represented as the bitwise opposite of
  252. ii = abs(ii) - 1 # the positive-zero number n-1.
  253. # make bits
  254. bb = BitArray()
  255. while ii > 0:
  256. bb += str(ii % 2)
  257. ii = ii >> 1
  258. bb.Reverse()
  259. # justify
  260. bb = "0" + str(bb) # always need the sign bit in front
  261. if n is not None:
  262. if len(bb) > n:
  263. raise ValueError("signedIntToBits fail: len larger than padlength.")
  264. bb = bb.rjust(n, "0")
  265. # was it negative? (then opposite bits)
  266. if i < 0:
  267. bb = bb.replace("0", "x").replace("1", "0").replace("x", "1")
  268. # done
  269. return BitArray(bb)
  270. def twitsToBits(arr):
  271. """Given a few (signed) numbers, store them
  272. as compactly as possible in the wat specifief by the swf format.
  273. The numbers are multiplied by 20, assuming they
  274. are twits.
  275. Can be used to make the RECT record.
  276. """
  277. # first determine length using non justified bit strings
  278. maxlen = 1
  279. for i in arr:
  280. tmp = len(signedIntToBits(i * 20))
  281. if tmp > maxlen:
  282. maxlen = tmp
  283. # build array
  284. bits = intToBits(maxlen, 5)
  285. for i in arr:
  286. bits += signedIntToBits(i * 20, maxlen)
  287. return bits
  288. def floatsToBits(arr):
  289. """Given a few (signed) numbers, convert them to bits,
  290. stored as FB (float bit values). We always use 16.16.
  291. Negative numbers are not (yet) possible, because I don't
  292. know how the're implemented (ambiguity).
  293. """
  294. bits = intToBits(31, 5) # 32 does not fit in 5 bits!
  295. for i in arr:
  296. if i < 0:
  297. raise ValueError("Dit not implement negative floats!")
  298. i1 = int(i)
  299. i2 = i - i1
  300. bits += intToBits(i1, 15)
  301. bits += intToBits(i2 * 2 ** 16, 16)
  302. return bits
  303. def _readFrom(fp, n):
  304. bb = binary_type()
  305. try:
  306. while len(bb) < n:
  307. tmp = fp.read(n - len(bb))
  308. bb += tmp
  309. if not tmp:
  310. break
  311. except EOFError:
  312. pass
  313. return bb
  314. # Base Tag
  315. class Tag:
  316. def __init__(self):
  317. self.bytes = binary_type()
  318. self.tagtype = -1
  319. def ProcessTag(self):
  320. """Implement this to create the tag."""
  321. raise NotImplementedError()
  322. def GetTag(self):
  323. """Calls processTag and attaches the header."""
  324. self.ProcessTag()
  325. # tag to binary
  326. bits = intToBits(self.tagtype, 10)
  327. # complete header uint16 thing
  328. bits += "1" * 6 # = 63 = 0x3f
  329. # make uint16
  330. bb = intToUint16(int(str(bits), 2))
  331. # now add 32bit length descriptor
  332. bb += intToUint32(len(self.bytes))
  333. # done, attach and return
  334. bb += self.bytes
  335. return bb
  336. def MakeRectRecord(self, xmin, xmax, ymin, ymax):
  337. """Simply uses makeCompactArray to produce
  338. a RECT Record."""
  339. return twitsToBits([xmin, xmax, ymin, ymax])
  340. def MakeMatrixRecord(self, scale_xy=None, rot_xy=None, trans_xy=None):
  341. # empty matrix?
  342. if scale_xy is None and rot_xy is None and trans_xy is None:
  343. return "0" * 8
  344. # init
  345. bits = BitArray()
  346. # scale
  347. if scale_xy:
  348. bits += "1"
  349. bits += floatsToBits([scale_xy[0], scale_xy[1]])
  350. else:
  351. bits += "0"
  352. # rotation
  353. if rot_xy:
  354. bits += "1"
  355. bits += floatsToBits([rot_xy[0], rot_xy[1]])
  356. else:
  357. bits += "0"
  358. # translation (no flag here)
  359. if trans_xy:
  360. bits += twitsToBits([trans_xy[0], trans_xy[1]])
  361. else:
  362. bits += twitsToBits([0, 0])
  363. # done
  364. return bits
  365. # Control tags
  366. class ControlTag(Tag):
  367. def __init__(self):
  368. Tag.__init__(self)
  369. class FileAttributesTag(ControlTag):
  370. def __init__(self):
  371. ControlTag.__init__(self)
  372. self.tagtype = 69
  373. def ProcessTag(self):
  374. self.bytes = "\x00".encode("ascii") * (1 + 3)
  375. class ShowFrameTag(ControlTag):
  376. def __init__(self):
  377. ControlTag.__init__(self)
  378. self.tagtype = 1
  379. def ProcessTag(self):
  380. self.bytes = binary_type()
  381. class SetBackgroundTag(ControlTag):
  382. """Set the color in 0-255, or 0-1 (if floats given)."""
  383. def __init__(self, *rgb):
  384. self.tagtype = 9
  385. if len(rgb) == 1:
  386. rgb = rgb[0]
  387. self.rgb = rgb
  388. def ProcessTag(self):
  389. bb = binary_type()
  390. for i in range(3):
  391. clr = self.rgb[i]
  392. if isinstance(clr, float):
  393. clr = clr * 255
  394. bb += intToUint8(clr)
  395. self.bytes = bb
  396. class DoActionTag(Tag):
  397. def __init__(self, action="stop"):
  398. Tag.__init__(self)
  399. self.tagtype = 12
  400. self.actions = [action]
  401. def Append(self, action):
  402. self.actions.append(action)
  403. def ProcessTag(self):
  404. bb = binary_type()
  405. for action in self.actions:
  406. action = action.lower()
  407. if action == "stop":
  408. bb += "\x07".encode("ascii")
  409. elif action == "play":
  410. bb += "\x06".encode("ascii")
  411. else:
  412. print("warning, unknown action: %s" % action)
  413. bb += intToUint8(0)
  414. self.bytes = bb
  415. # Definition tags
  416. class DefinitionTag(Tag):
  417. counter = 0 # to give automatically id's
  418. def __init__(self):
  419. Tag.__init__(self)
  420. DefinitionTag.counter += 1
  421. self.id = DefinitionTag.counter # id in dictionary
  422. class BitmapTag(DefinitionTag):
  423. def __init__(self, im):
  424. DefinitionTag.__init__(self)
  425. self.tagtype = 36 # DefineBitsLossless2
  426. # convert image (note that format is ARGB)
  427. # even a grayscale image is stored in ARGB, nevertheless,
  428. # the fabilous deflate compression will make it that not much
  429. # more data is required for storing (25% or so, and less than 10%
  430. # when storing RGB as ARGB).
  431. if len(im.shape) == 3:
  432. if im.shape[2] in [3, 4]:
  433. tmp = np.ones((im.shape[0], im.shape[1], 4), dtype=np.uint8) * 255
  434. for i in range(3):
  435. tmp[:, :, i + 1] = im[:, :, i]
  436. if im.shape[2] == 4:
  437. tmp[:, :, 0] = im[:, :, 3] # swap channel where alpha is in
  438. else:
  439. raise ValueError("Invalid shape to be an image.")
  440. elif len(im.shape) == 2:
  441. tmp = np.ones((im.shape[0], im.shape[1], 4), dtype=np.uint8) * 255
  442. for i in range(3):
  443. tmp[:, :, i + 1] = im[:, :]
  444. else:
  445. raise ValueError("Invalid shape to be an image.")
  446. # we changed the image to uint8 4 channels.
  447. # now compress!
  448. self._data = zlib.compress(tmp.tostring(), zlib.DEFLATED)
  449. self.imshape = im.shape
  450. def ProcessTag(self):
  451. # build tag
  452. bb = binary_type()
  453. bb += intToUint16(self.id) # CharacterID
  454. bb += intToUint8(5) # BitmapFormat
  455. bb += intToUint16(self.imshape[1]) # BitmapWidth
  456. bb += intToUint16(self.imshape[0]) # BitmapHeight
  457. bb += self._data # ZlibBitmapData
  458. self.bytes = bb
  459. class PlaceObjectTag(ControlTag):
  460. def __init__(self, depth, idToPlace=None, xy=(0, 0), move=False):
  461. ControlTag.__init__(self)
  462. self.tagtype = 26
  463. self.depth = depth
  464. self.idToPlace = idToPlace
  465. self.xy = xy
  466. self.move = move
  467. def ProcessTag(self):
  468. # retrieve stuff
  469. depth = self.depth
  470. xy = self.xy
  471. id = self.idToPlace
  472. # build PlaceObject2
  473. bb = binary_type()
  474. if self.move:
  475. bb += "\x07".encode("ascii")
  476. else:
  477. bb += "\x06".encode("ascii") # (8 bit flags): 4:matrix, 2:character, 1:move
  478. bb += intToUint16(depth) # Depth
  479. bb += intToUint16(id) # character id
  480. bb += self.MakeMatrixRecord(trans_xy=xy).ToBytes() # MATRIX record
  481. self.bytes = bb
  482. class ShapeTag(DefinitionTag):
  483. def __init__(self, bitmapId, xy, wh):
  484. DefinitionTag.__init__(self)
  485. self.tagtype = 2
  486. self.bitmapId = bitmapId
  487. self.xy = xy
  488. self.wh = wh
  489. def ProcessTag(self):
  490. """Returns a defineshape tag. with a bitmap fill"""
  491. bb = binary_type()
  492. bb += intToUint16(self.id)
  493. xy, wh = self.xy, self.wh
  494. tmp = self.MakeRectRecord(xy[0], wh[0], xy[1], wh[1]) # ShapeBounds
  495. bb += tmp.ToBytes()
  496. # make SHAPEWITHSTYLE structure
  497. # first entry: FILLSTYLEARRAY with in it a single fill style
  498. bb += intToUint8(1) # FillStyleCount
  499. bb += "\x41".encode(
  500. "ascii"
  501. ) # FillStyleType (0x41 or 0x43, latter is non-smoothed)
  502. bb += intToUint16(self.bitmapId) # BitmapId
  503. # bb += '\x00' # BitmapMatrix (empty matrix with leftover bits filled)
  504. bb += self.MakeMatrixRecord(scale_xy=(20, 20)).ToBytes()
  505. # # first entry: FILLSTYLEARRAY with in it a single fill style
  506. # bb += intToUint8(1) # FillStyleCount
  507. # bb += '\x00' # solid fill
  508. # bb += '\x00\x00\xff' # color
  509. # second entry: LINESTYLEARRAY with a single line style
  510. bb += intToUint8(0) # LineStyleCount
  511. # bb += intToUint16(0*20) # Width
  512. # bb += '\x00\xff\x00' # Color
  513. # third and fourth entry: NumFillBits and NumLineBits (4 bits each)
  514. # I each give them four bits, so 16 styles possible.
  515. bb += "\x44".encode("ascii")
  516. self.bytes = bb
  517. # last entries: SHAPERECORDs ... (individual shape records not aligned)
  518. # STYLECHANGERECORD
  519. bits = BitArray()
  520. bits += self.MakeStyleChangeRecord(0, 1, moveTo=(self.wh[0], self.wh[1]))
  521. # STRAIGHTEDGERECORD 4x
  522. bits += self.MakeStraightEdgeRecord(-self.wh[0], 0)
  523. bits += self.MakeStraightEdgeRecord(0, -self.wh[1])
  524. bits += self.MakeStraightEdgeRecord(self.wh[0], 0)
  525. bits += self.MakeStraightEdgeRecord(0, self.wh[1])
  526. # ENDSHAPRECORD
  527. bits += self.MakeEndShapeRecord()
  528. self.bytes += bits.ToBytes()
  529. # done
  530. # self.bytes = bb
  531. def MakeStyleChangeRecord(self, lineStyle=None, fillStyle=None, moveTo=None):
  532. # first 6 flags
  533. # Note that we use FillStyle1. If we don't flash (at least 8) does not
  534. # recognize the frames properly when importing to library.
  535. bits = BitArray()
  536. bits += "0" # TypeFlag (not an edge record)
  537. bits += "0" # StateNewStyles (only for DefineShape2 and Defineshape3)
  538. if lineStyle:
  539. bits += "1" # StateLineStyle
  540. else:
  541. bits += "0"
  542. if fillStyle:
  543. bits += "1" # StateFillStyle1
  544. else:
  545. bits += "0"
  546. bits += "0" # StateFillStyle0
  547. if moveTo:
  548. bits += "1" # StateMoveTo
  549. else:
  550. bits += "0"
  551. # give information
  552. # todo: nbits for fillStyle and lineStyle is hard coded.
  553. if moveTo:
  554. bits += twitsToBits([moveTo[0], moveTo[1]])
  555. if fillStyle:
  556. bits += intToBits(fillStyle, 4)
  557. if lineStyle:
  558. bits += intToBits(lineStyle, 4)
  559. return bits
  560. # return bitsToBytes(bits)
  561. def MakeStraightEdgeRecord(self, *dxdy):
  562. if len(dxdy) == 1:
  563. dxdy = dxdy[0]
  564. # determine required number of bits
  565. xbits = signedIntToBits(dxdy[0] * 20)
  566. ybits = signedIntToBits(dxdy[1] * 20)
  567. nbits = max([len(xbits), len(ybits)])
  568. bits = BitArray()
  569. bits += "11" # TypeFlag and StraightFlag
  570. bits += intToBits(nbits - 2, 4)
  571. bits += "1" # GeneralLineFlag
  572. bits += signedIntToBits(dxdy[0] * 20, nbits)
  573. bits += signedIntToBits(dxdy[1] * 20, nbits)
  574. # note: I do not make use of vertical/horizontal only lines...
  575. return bits
  576. # return bitsToBytes(bits)
  577. def MakeEndShapeRecord(self):
  578. bits = BitArray()
  579. bits += "0" # TypeFlag: no edge
  580. bits += "0" * 5 # EndOfShape
  581. return bits
  582. # return bitsToBytes(bits)
  583. # Last few functions
  584. def buildFile(fp, taglist, nframes=1, framesize=(500, 500), fps=10, version=8):
  585. """Give the given file (as bytes) a header."""
  586. # compose header
  587. bb = binary_type()
  588. bb += "F".encode("ascii") # uncompressed
  589. bb += "WS".encode("ascii") # signature bytes
  590. bb += intToUint8(version) # version
  591. bb += "0000".encode("ascii") # FileLength (leave open for now)
  592. bb += Tag().MakeRectRecord(0, framesize[0], 0, framesize[1]).ToBytes()
  593. bb += intToUint8(0) + intToUint8(fps) # FrameRate
  594. bb += intToUint16(nframes)
  595. fp.write(bb)
  596. # produce all tags
  597. for tag in taglist:
  598. fp.write(tag.GetTag())
  599. # finish with end tag
  600. fp.write("\x00\x00".encode("ascii"))
  601. # set size
  602. sze = fp.tell()
  603. fp.seek(4)
  604. fp.write(intToUint32(sze))
  605. def writeSwf(filename, images, duration=0.1, repeat=True):
  606. """Write an swf-file from the specified images. If repeat is False,
  607. the movie is finished with a stop action. Duration may also
  608. be a list with durations for each frame (note that the duration
  609. for each frame is always an integer amount of the minimum duration.)
  610. Images should be a list consisting of PIL images or numpy arrays.
  611. The latter should be between 0 and 255 for integer types, and
  612. between 0 and 1 for float types.
  613. """
  614. # Check Numpy
  615. if np is None:
  616. raise RuntimeError("Need Numpy to write an SWF file.")
  617. # Check images (make all Numpy)
  618. images2 = []
  619. images = checkImages(images)
  620. if not images:
  621. raise ValueError("Image list is empty!")
  622. for im in images:
  623. if PIL and isinstance(im, PIL.Image.Image):
  624. if im.mode == "P":
  625. im = im.convert()
  626. im = np.asarray(im)
  627. if len(im.shape) == 0:
  628. raise MemoryError("Too little memory to convert PIL image to array")
  629. images2.append(im)
  630. # Init
  631. taglist = [FileAttributesTag(), SetBackgroundTag(0, 0, 0)]
  632. # Check duration
  633. if hasattr(duration, "__len__"):
  634. if len(duration) == len(images2):
  635. duration = [d for d in duration]
  636. else:
  637. raise ValueError("len(duration) doesn't match amount of images.")
  638. else:
  639. duration = [duration for im in images2]
  640. # Build delays list
  641. minDuration = float(min(duration))
  642. delays = [round(d / minDuration) for d in duration]
  643. delays = [max(1, int(d)) for d in delays]
  644. # Get FPS
  645. fps = 1.0 / minDuration
  646. # Produce series of tags for each image
  647. nframes = 0
  648. for im in images2:
  649. bm = BitmapTag(im)
  650. wh = (im.shape[1], im.shape[0])
  651. sh = ShapeTag(bm.id, (0, 0), wh)
  652. po = PlaceObjectTag(1, sh.id, move=nframes > 0)
  653. taglist.extend([bm, sh, po])
  654. for i in range(delays[nframes]):
  655. taglist.append(ShowFrameTag())
  656. nframes += 1
  657. if not repeat:
  658. taglist.append(DoActionTag("stop"))
  659. # Build file
  660. fp = open(filename, "wb")
  661. try:
  662. buildFile(fp, taglist, nframes=nframes, framesize=wh, fps=fps)
  663. except Exception:
  664. raise
  665. finally:
  666. fp.close()
  667. def _readPixels(bb, i, tagType, L1):
  668. """With pf's seed after the recordheader, reads the pixeldata."""
  669. # Check Numpy
  670. if np is None:
  671. raise RuntimeError("Need Numpy to read an SWF file.")
  672. # Get info
  673. # charId = bb[i : i + 2] # unused
  674. i += 2
  675. format = ord(bb[i : i + 1])
  676. i += 1
  677. width = bitsToInt(bb[i : i + 2], 16)
  678. i += 2
  679. height = bitsToInt(bb[i : i + 2], 16)
  680. i += 2
  681. # If we can, get pixeldata and make numpy array
  682. if format != 5:
  683. print("Can only read 24bit or 32bit RGB(A) lossless images.")
  684. else:
  685. # Read byte data
  686. offset = 2 + 1 + 2 + 2 # all the info bits
  687. bb2 = bb[i : i + (L1 - offset)]
  688. # Decompress and make numpy array
  689. data = zlib.decompress(bb2)
  690. a = np.frombuffer(data, dtype=np.uint8)
  691. # Set shape
  692. if tagType == 20:
  693. # DefineBitsLossless - RGB data
  694. try:
  695. a.shape = height, width, 3
  696. except Exception:
  697. # Byte align stuff might cause troubles
  698. print("Cannot read image due to byte alignment")
  699. if tagType == 36:
  700. # DefineBitsLossless2 - ARGB data
  701. a.shape = height, width, 4
  702. # Swap alpha channel to make RGBA
  703. b = a
  704. a = np.zeros_like(a)
  705. a[:, :, 0] = b[:, :, 1]
  706. a[:, :, 1] = b[:, :, 2]
  707. a[:, :, 2] = b[:, :, 3]
  708. a[:, :, 3] = b[:, :, 0]
  709. return a
  710. def readSwf(filename, asNumpy=True):
  711. """Read all images from an SWF (shockwave flash) file. Returns a list
  712. of numpy arrays, or, if asNumpy is false, a list if PIL images.
  713. Limitation: only read the PNG encoded images (not the JPG encoded ones).
  714. """
  715. # Check whether it exists
  716. if not os.path.isfile(filename):
  717. raise IOError("File not found: " + str(filename))
  718. # Check PIL
  719. if (not asNumpy) and (PIL is None):
  720. raise RuntimeError("Need PIL to return as PIL images.")
  721. # Check Numpy
  722. if np is None:
  723. raise RuntimeError("Need Numpy to read SWF files.")
  724. # Init images
  725. images = []
  726. # Open file and read all
  727. fp = open(filename, "rb")
  728. bb = fp.read()
  729. try:
  730. # Check opening tag
  731. tmp = bb[0:3].decode("ascii", "ignore")
  732. if tmp.upper() == "FWS":
  733. pass # ok
  734. elif tmp.upper() == "CWS":
  735. # Decompress movie
  736. bb = bb[:8] + zlib.decompress(bb[8:])
  737. else:
  738. raise IOError("Not a valid SWF file: " + str(filename))
  739. # Set filepointer at first tag (skipping framesize RECT and two uin16's
  740. i = 8
  741. nbits = bitsToInt(bb[i : i + 1], 5) # skip FrameSize
  742. nbits = 5 + nbits * 4
  743. Lrect = nbits / 8.0
  744. if Lrect % 1:
  745. Lrect += 1
  746. Lrect = int(Lrect)
  747. i += Lrect + 4
  748. # Iterate over the tags
  749. counter = 0
  750. while True:
  751. counter += 1
  752. # Get tag header
  753. head = bb[i : i + 6]
  754. if not head:
  755. break # Done (we missed end tag)
  756. # Determine type and length
  757. T, L1, L2 = getTypeAndLen(head)
  758. if not L2:
  759. print("Invalid tag length, could not proceed")
  760. break
  761. # print(T, L2)
  762. # Read image if we can
  763. if T in [20, 36]:
  764. im = _readPixels(bb, i + 6, T, L1)
  765. if im is not None:
  766. images.append(im)
  767. elif T in [6, 21, 35, 90]:
  768. print("Ignoring JPEG image: cannot read JPEG.")
  769. else:
  770. pass # Not an image tag
  771. # Detect end tag
  772. if T == 0:
  773. break
  774. # Next tag!
  775. i += L2
  776. finally:
  777. fp.close()
  778. # Convert to normal PIL images if needed
  779. if not asNumpy:
  780. images2 = images
  781. images = []
  782. for im in images2:
  783. images.append(PIL.Image.fromarray(im))
  784. # Done
  785. return images