images2swf.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  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. if PY3:
  182. def intToUint32(i):
  183. return int(i).to_bytes(4, "little")
  184. def intToUint16(i):
  185. return int(i).to_bytes(2, "little")
  186. def intToUint8(i):
  187. return int(i).to_bytes(1, "little")
  188. else:
  189. def intToUint32(i):
  190. number = int(i)
  191. n1, n2, n3, n4 = 1, 256, 256 * 256, 256 * 256 * 256
  192. b4, number = number // n4, number % n4
  193. b3, number = number // n3, number % n3
  194. b2, number = number // n2, number % n2
  195. b1 = number
  196. return chr(b1) + chr(b2) + chr(b3) + chr(b4)
  197. def intToUint16(i):
  198. i = int(i)
  199. # divide in two parts (bytes)
  200. i1 = i % 256
  201. i2 = int(i // 256)
  202. # make string (little endian)
  203. return chr(i1) + chr(i2)
  204. def intToUint8(i):
  205. return chr(int(i))
  206. def intToBits(i, n=None):
  207. """convert int to a string of bits (0's and 1's in a string),
  208. pad to n elements. Convert back using int(ss,2)."""
  209. ii = i
  210. # make bits
  211. bb = BitArray()
  212. while ii > 0:
  213. bb += str(ii % 2)
  214. ii = ii >> 1
  215. bb.Reverse()
  216. # justify
  217. if n is not None:
  218. if len(bb) > n:
  219. raise ValueError("intToBits fail: len larger than padlength.")
  220. bb = str(bb).rjust(n, "0")
  221. # done
  222. return BitArray(bb)
  223. def bitsToInt(bb, n=8):
  224. # Init
  225. value = ""
  226. # Get value in bits
  227. for i in range(len(bb)):
  228. b = bb[i : i + 1]
  229. tmp = bin(ord(b))[2:]
  230. # value += tmp.rjust(8,'0')
  231. value = tmp.rjust(8, "0") + value
  232. # Make decimal
  233. return int(value[:n], 2)
  234. def getTypeAndLen(bb):
  235. """bb should be 6 bytes at least
  236. Return (type, length, length_of_full_tag)
  237. """
  238. # Init
  239. value = ""
  240. # Get first 16 bits
  241. for i in range(2):
  242. b = bb[i : i + 1]
  243. tmp = bin(ord(b))[2:]
  244. # value += tmp.rjust(8,'0')
  245. value = tmp.rjust(8, "0") + value
  246. # Get type and length
  247. type = int(value[:10], 2)
  248. L = int(value[10:], 2)
  249. L2 = L + 2
  250. # Long tag header?
  251. if L == 63: # '111111'
  252. value = ""
  253. for i in range(2, 6):
  254. b = bb[i : i + 1] # becomes a single-byte bytes() on both PY3 and PY2
  255. tmp = bin(ord(b))[2:]
  256. # value += tmp.rjust(8,'0')
  257. value = tmp.rjust(8, "0") + value
  258. L = int(value, 2)
  259. L2 = L + 6
  260. # Done
  261. return type, L, L2
  262. def signedIntToBits(i, n=None):
  263. """convert signed int to a string of bits (0's and 1's in a string),
  264. pad to n elements. Negative numbers are stored in 2's complement bit
  265. patterns, thus positive numbers always start with a 0.
  266. """
  267. # negative number?
  268. ii = i
  269. if i < 0:
  270. # A negative number, -n, is represented as the bitwise opposite of
  271. ii = abs(ii) - 1 # the positive-zero number n-1.
  272. # make bits
  273. bb = BitArray()
  274. while ii > 0:
  275. bb += str(ii % 2)
  276. ii = ii >> 1
  277. bb.Reverse()
  278. # justify
  279. bb = "0" + str(bb) # always need the sign bit in front
  280. if n is not None:
  281. if len(bb) > n:
  282. raise ValueError("signedIntToBits fail: len larger than padlength.")
  283. bb = bb.rjust(n, "0")
  284. # was it negative? (then opposite bits)
  285. if i < 0:
  286. bb = bb.replace("0", "x").replace("1", "0").replace("x", "1")
  287. # done
  288. return BitArray(bb)
  289. def twitsToBits(arr):
  290. """Given a few (signed) numbers, store them
  291. as compactly as possible in the wat specifief by the swf format.
  292. The numbers are multiplied by 20, assuming they
  293. are twits.
  294. Can be used to make the RECT record.
  295. """
  296. # first determine length using non justified bit strings
  297. maxlen = 1
  298. for i in arr:
  299. tmp = len(signedIntToBits(i * 20))
  300. if tmp > maxlen:
  301. maxlen = tmp
  302. # build array
  303. bits = intToBits(maxlen, 5)
  304. for i in arr:
  305. bits += signedIntToBits(i * 20, maxlen)
  306. return bits
  307. def floatsToBits(arr):
  308. """Given a few (signed) numbers, convert them to bits,
  309. stored as FB (float bit values). We always use 16.16.
  310. Negative numbers are not (yet) possible, because I don't
  311. know how the're implemented (ambiguity).
  312. """
  313. bits = intToBits(31, 5) # 32 does not fit in 5 bits!
  314. for i in arr:
  315. if i < 0:
  316. raise ValueError("Dit not implement negative floats!")
  317. i1 = int(i)
  318. i2 = i - i1
  319. bits += intToBits(i1, 15)
  320. bits += intToBits(i2 * 2 ** 16, 16)
  321. return bits
  322. def _readFrom(fp, n):
  323. bb = binary_type()
  324. try:
  325. while len(bb) < n:
  326. tmp = fp.read(n - len(bb))
  327. bb += tmp
  328. if not tmp:
  329. break
  330. except EOFError:
  331. pass
  332. return bb
  333. ## Base Tag
  334. class Tag:
  335. def __init__(self):
  336. self.bytes = binary_type()
  337. self.tagtype = -1
  338. def ProcessTag(self):
  339. """ Implement this to create the tag. """
  340. raise NotImplementedError()
  341. def GetTag(self):
  342. """ Calls processTag and attaches the header. """
  343. self.ProcessTag()
  344. # tag to binary
  345. bits = intToBits(self.tagtype, 10)
  346. # complete header uint16 thing
  347. bits += "1" * 6 # = 63 = 0x3f
  348. # make uint16
  349. bb = intToUint16(int(str(bits), 2))
  350. # now add 32bit length descriptor
  351. bb += intToUint32(len(self.bytes))
  352. # done, attach and return
  353. bb += self.bytes
  354. return bb
  355. def MakeRectRecord(self, xmin, xmax, ymin, ymax):
  356. """Simply uses makeCompactArray to produce
  357. a RECT Record."""
  358. return twitsToBits([xmin, xmax, ymin, ymax])
  359. def MakeMatrixRecord(self, scale_xy=None, rot_xy=None, trans_xy=None):
  360. # empty matrix?
  361. if scale_xy is None and rot_xy is None and trans_xy is None:
  362. return "0" * 8
  363. # init
  364. bits = BitArray()
  365. # scale
  366. if scale_xy:
  367. bits += "1"
  368. bits += floatsToBits([scale_xy[0], scale_xy[1]])
  369. else:
  370. bits += "0"
  371. # rotation
  372. if rot_xy:
  373. bits += "1"
  374. bits += floatsToBits([rot_xy[0], rot_xy[1]])
  375. else:
  376. bits += "0"
  377. # translation (no flag here)
  378. if trans_xy:
  379. bits += twitsToBits([trans_xy[0], trans_xy[1]])
  380. else:
  381. bits += twitsToBits([0, 0])
  382. # done
  383. return bits
  384. ## Control tags
  385. class ControlTag(Tag):
  386. def __init__(self):
  387. Tag.__init__(self)
  388. class FileAttributesTag(ControlTag):
  389. def __init__(self):
  390. ControlTag.__init__(self)
  391. self.tagtype = 69
  392. def ProcessTag(self):
  393. self.bytes = "\x00".encode("ascii") * (1 + 3)
  394. class ShowFrameTag(ControlTag):
  395. def __init__(self):
  396. ControlTag.__init__(self)
  397. self.tagtype = 1
  398. def ProcessTag(self):
  399. self.bytes = binary_type()
  400. class SetBackgroundTag(ControlTag):
  401. """ Set the color in 0-255, or 0-1 (if floats given). """
  402. def __init__(self, *rgb):
  403. self.tagtype = 9
  404. if len(rgb) == 1:
  405. rgb = rgb[0]
  406. self.rgb = rgb
  407. def ProcessTag(self):
  408. bb = binary_type()
  409. for i in range(3):
  410. clr = self.rgb[i]
  411. if isinstance(clr, float):
  412. clr = clr * 255
  413. bb += intToUint8(clr)
  414. self.bytes = bb
  415. class DoActionTag(Tag):
  416. def __init__(self, action="stop"):
  417. Tag.__init__(self)
  418. self.tagtype = 12
  419. self.actions = [action]
  420. def Append(self, action):
  421. self.actions.append(action)
  422. def ProcessTag(self):
  423. bb = binary_type()
  424. for action in self.actions:
  425. action = action.lower()
  426. if action == "stop":
  427. bb += "\x07".encode("ascii")
  428. elif action == "play":
  429. bb += "\x06".encode("ascii")
  430. else:
  431. print("warning, unknown action: %s" % action)
  432. bb += intToUint8(0)
  433. self.bytes = bb
  434. ## Definition tags
  435. class DefinitionTag(Tag):
  436. counter = 0 # to give automatically id's
  437. def __init__(self):
  438. Tag.__init__(self)
  439. DefinitionTag.counter += 1
  440. self.id = DefinitionTag.counter # id in dictionary
  441. class BitmapTag(DefinitionTag):
  442. def __init__(self, im):
  443. DefinitionTag.__init__(self)
  444. self.tagtype = 36 # DefineBitsLossless2
  445. # convert image (note that format is ARGB)
  446. # even a grayscale image is stored in ARGB, nevertheless,
  447. # the fabilous deflate compression will make it that not much
  448. # more data is required for storing (25% or so, and less than 10%
  449. # when storing RGB as ARGB).
  450. if len(im.shape) == 3:
  451. if im.shape[2] in [3, 4]:
  452. tmp = np.ones((im.shape[0], im.shape[1], 4), dtype=np.uint8) * 255
  453. for i in range(3):
  454. tmp[:, :, i + 1] = im[:, :, i]
  455. if im.shape[2] == 4:
  456. tmp[:, :, 0] = im[:, :, 3] # swap channel where alpha is in
  457. else:
  458. raise ValueError("Invalid shape to be an image.")
  459. elif len(im.shape) == 2:
  460. tmp = np.ones((im.shape[0], im.shape[1], 4), dtype=np.uint8) * 255
  461. for i in range(3):
  462. tmp[:, :, i + 1] = im[:, :]
  463. else:
  464. raise ValueError("Invalid shape to be an image.")
  465. # we changed the image to uint8 4 channels.
  466. # now compress!
  467. self._data = zlib.compress(tmp.tostring(), zlib.DEFLATED)
  468. self.imshape = im.shape
  469. def ProcessTag(self):
  470. # build tag
  471. bb = binary_type()
  472. bb += intToUint16(self.id) # CharacterID
  473. bb += intToUint8(5) # BitmapFormat
  474. bb += intToUint16(self.imshape[1]) # BitmapWidth
  475. bb += intToUint16(self.imshape[0]) # BitmapHeight
  476. bb += self._data # ZlibBitmapData
  477. self.bytes = bb
  478. class PlaceObjectTag(ControlTag):
  479. def __init__(self, depth, idToPlace=None, xy=(0, 0), move=False):
  480. ControlTag.__init__(self)
  481. self.tagtype = 26
  482. self.depth = depth
  483. self.idToPlace = idToPlace
  484. self.xy = xy
  485. self.move = move
  486. def ProcessTag(self):
  487. # retrieve stuff
  488. depth = self.depth
  489. xy = self.xy
  490. id = self.idToPlace
  491. # build PlaceObject2
  492. bb = binary_type()
  493. if self.move:
  494. bb += "\x07".encode("ascii")
  495. else:
  496. bb += "\x06".encode("ascii") # (8 bit flags): 4:matrix, 2:character, 1:move
  497. bb += intToUint16(depth) # Depth
  498. bb += intToUint16(id) # character id
  499. bb += self.MakeMatrixRecord(trans_xy=xy).ToBytes() # MATRIX record
  500. self.bytes = bb
  501. class ShapeTag(DefinitionTag):
  502. def __init__(self, bitmapId, xy, wh):
  503. DefinitionTag.__init__(self)
  504. self.tagtype = 2
  505. self.bitmapId = bitmapId
  506. self.xy = xy
  507. self.wh = wh
  508. def ProcessTag(self):
  509. """ Returns a defineshape tag. with a bitmap fill """
  510. bb = binary_type()
  511. bb += intToUint16(self.id)
  512. xy, wh = self.xy, self.wh
  513. tmp = self.MakeRectRecord(xy[0], wh[0], xy[1], wh[1]) # ShapeBounds
  514. bb += tmp.ToBytes()
  515. # make SHAPEWITHSTYLE structure
  516. # first entry: FILLSTYLEARRAY with in it a single fill style
  517. bb += intToUint8(1) # FillStyleCount
  518. bb += "\x41".encode(
  519. "ascii"
  520. ) # FillStyleType (0x41 or 0x43, latter is non-smoothed)
  521. bb += intToUint16(self.bitmapId) # BitmapId
  522. # bb += '\x00' # BitmapMatrix (empty matrix with leftover bits filled)
  523. bb += self.MakeMatrixRecord(scale_xy=(20, 20)).ToBytes()
  524. # # first entry: FILLSTYLEARRAY with in it a single fill style
  525. # bb += intToUint8(1) # FillStyleCount
  526. # bb += '\x00' # solid fill
  527. # bb += '\x00\x00\xff' # color
  528. # second entry: LINESTYLEARRAY with a single line style
  529. bb += intToUint8(0) # LineStyleCount
  530. # bb += intToUint16(0*20) # Width
  531. # bb += '\x00\xff\x00' # Color
  532. # third and fourth entry: NumFillBits and NumLineBits (4 bits each)
  533. # I each give them four bits, so 16 styles possible.
  534. bb += "\x44".encode("ascii")
  535. self.bytes = bb
  536. # last entries: SHAPERECORDs ... (individual shape records not aligned)
  537. # STYLECHANGERECORD
  538. bits = BitArray()
  539. bits += self.MakeStyleChangeRecord(0, 1, moveTo=(self.wh[0], self.wh[1]))
  540. # STRAIGHTEDGERECORD 4x
  541. bits += self.MakeStraightEdgeRecord(-self.wh[0], 0)
  542. bits += self.MakeStraightEdgeRecord(0, -self.wh[1])
  543. bits += self.MakeStraightEdgeRecord(self.wh[0], 0)
  544. bits += self.MakeStraightEdgeRecord(0, self.wh[1])
  545. # ENDSHAPRECORD
  546. bits += self.MakeEndShapeRecord()
  547. self.bytes += bits.ToBytes()
  548. # done
  549. # self.bytes = bb
  550. def MakeStyleChangeRecord(self, lineStyle=None, fillStyle=None, moveTo=None):
  551. # first 6 flags
  552. # Note that we use FillStyle1. If we don't flash (at least 8) does not
  553. # recognize the frames properly when importing to library.
  554. bits = BitArray()
  555. bits += "0" # TypeFlag (not an edge record)
  556. bits += "0" # StateNewStyles (only for DefineShape2 and Defineshape3)
  557. if lineStyle:
  558. bits += "1" # StateLineStyle
  559. else:
  560. bits += "0"
  561. if fillStyle:
  562. bits += "1" # StateFillStyle1
  563. else:
  564. bits += "0"
  565. bits += "0" # StateFillStyle0
  566. if moveTo:
  567. bits += "1" # StateMoveTo
  568. else:
  569. bits += "0"
  570. # give information
  571. # todo: nbits for fillStyle and lineStyle is hard coded.
  572. if moveTo:
  573. bits += twitsToBits([moveTo[0], moveTo[1]])
  574. if fillStyle:
  575. bits += intToBits(fillStyle, 4)
  576. if lineStyle:
  577. bits += intToBits(lineStyle, 4)
  578. return bits
  579. # return bitsToBytes(bits)
  580. def MakeStraightEdgeRecord(self, *dxdy):
  581. if len(dxdy) == 1:
  582. dxdy = dxdy[0]
  583. # determine required number of bits
  584. xbits = signedIntToBits(dxdy[0] * 20)
  585. ybits = signedIntToBits(dxdy[1] * 20)
  586. nbits = max([len(xbits), len(ybits)])
  587. bits = BitArray()
  588. bits += "11" # TypeFlag and StraightFlag
  589. bits += intToBits(nbits - 2, 4)
  590. bits += "1" # GeneralLineFlag
  591. bits += signedIntToBits(dxdy[0] * 20, nbits)
  592. bits += signedIntToBits(dxdy[1] * 20, nbits)
  593. # note: I do not make use of vertical/horizontal only lines...
  594. return bits
  595. # return bitsToBytes(bits)
  596. def MakeEndShapeRecord(self):
  597. bits = BitArray()
  598. bits += "0" # TypeFlag: no edge
  599. bits += "0" * 5 # EndOfShape
  600. return bits
  601. # return bitsToBytes(bits)
  602. ## Last few functions
  603. def buildFile(fp, taglist, nframes=1, framesize=(500, 500), fps=10, version=8):
  604. """ Give the given file (as bytes) a header. """
  605. # compose header
  606. bb = binary_type()
  607. bb += "F".encode("ascii") # uncompressed
  608. bb += "WS".encode("ascii") # signature bytes
  609. bb += intToUint8(version) # version
  610. bb += "0000".encode("ascii") # FileLength (leave open for now)
  611. bb += Tag().MakeRectRecord(0, framesize[0], 0, framesize[1]).ToBytes()
  612. bb += intToUint8(0) + intToUint8(fps) # FrameRate
  613. bb += intToUint16(nframes)
  614. fp.write(bb)
  615. # produce all tags
  616. for tag in taglist:
  617. fp.write(tag.GetTag())
  618. # finish with end tag
  619. fp.write("\x00\x00".encode("ascii"))
  620. # set size
  621. sze = fp.tell()
  622. fp.seek(4)
  623. fp.write(intToUint32(sze))
  624. def writeSwf(filename, images, duration=0.1, repeat=True):
  625. """Write an swf-file from the specified images. If repeat is False,
  626. the movie is finished with a stop action. Duration may also
  627. be a list with durations for each frame (note that the duration
  628. for each frame is always an integer amount of the minimum duration.)
  629. Images should be a list consisting of PIL images or numpy arrays.
  630. The latter should be between 0 and 255 for integer types, and
  631. between 0 and 1 for float types.
  632. """
  633. # Check Numpy
  634. if np is None:
  635. raise RuntimeError("Need Numpy to write an SWF file.")
  636. # Check images (make all Numpy)
  637. images2 = []
  638. images = checkImages(images)
  639. if not images:
  640. raise ValueError("Image list is empty!")
  641. for im in images:
  642. if PIL and isinstance(im, PIL.Image.Image):
  643. if im.mode == "P":
  644. im = im.convert()
  645. im = np.asarray(im)
  646. if len(im.shape) == 0:
  647. raise MemoryError("Too little memory to convert PIL image to array")
  648. images2.append(im)
  649. # Init
  650. taglist = [FileAttributesTag(), SetBackgroundTag(0, 0, 0)]
  651. # Check duration
  652. if hasattr(duration, "__len__"):
  653. if len(duration) == len(images2):
  654. duration = [d for d in duration]
  655. else:
  656. raise ValueError("len(duration) doesn't match amount of images.")
  657. else:
  658. duration = [duration for im in images2]
  659. # Build delays list
  660. minDuration = float(min(duration))
  661. delays = [round(d / minDuration) for d in duration]
  662. delays = [max(1, int(d)) for d in delays]
  663. # Get FPS
  664. fps = 1.0 / minDuration
  665. # Produce series of tags for each image
  666. nframes = 0
  667. for im in images2:
  668. bm = BitmapTag(im)
  669. wh = (im.shape[1], im.shape[0])
  670. sh = ShapeTag(bm.id, (0, 0), wh)
  671. po = PlaceObjectTag(1, sh.id, move=nframes > 0)
  672. taglist.extend([bm, sh, po])
  673. for i in range(delays[nframes]):
  674. taglist.append(ShowFrameTag())
  675. nframes += 1
  676. if not repeat:
  677. taglist.append(DoActionTag("stop"))
  678. # Build file
  679. fp = open(filename, "wb")
  680. try:
  681. buildFile(fp, taglist, nframes=nframes, framesize=wh, fps=fps)
  682. except Exception:
  683. raise
  684. finally:
  685. fp.close()
  686. def _readPixels(bb, i, tagType, L1):
  687. """With pf's seed after the recordheader, reads the pixeldata."""
  688. # Check Numpy
  689. if np is None:
  690. raise RuntimeError("Need Numpy to read an SWF file.")
  691. # Get info
  692. charId = bb[i : i + 2]
  693. i += 2
  694. format = ord(bb[i : i + 1])
  695. i += 1
  696. width = bitsToInt(bb[i : i + 2], 16)
  697. i += 2
  698. height = bitsToInt(bb[i : i + 2], 16)
  699. i += 2
  700. # If we can, get pixeldata and make nunmpy array
  701. if format != 5:
  702. print("Can only read 24bit or 32bit RGB(A) lossless images.")
  703. else:
  704. # Read byte data
  705. offset = 2 + 1 + 2 + 2 # all the info bits
  706. bb2 = bb[i : i + (L1 - offset)]
  707. # Decompress and make numpy array
  708. data = zlib.decompress(bb2)
  709. a = np.frombuffer(data, dtype=np.uint8)
  710. # Set shape
  711. if tagType == 20:
  712. # DefineBitsLossless - RGB data
  713. try:
  714. a.shape = height, width, 3
  715. except Exception:
  716. # Byte align stuff might cause troubles
  717. print("Cannot read image due to byte alignment")
  718. if tagType == 36:
  719. # DefineBitsLossless2 - ARGB data
  720. a.shape = height, width, 4
  721. # Swap alpha channel to make RGBA
  722. b = a
  723. a = np.zeros_like(a)
  724. a[:, :, 0] = b[:, :, 1]
  725. a[:, :, 1] = b[:, :, 2]
  726. a[:, :, 2] = b[:, :, 3]
  727. a[:, :, 3] = b[:, :, 0]
  728. return a
  729. def readSwf(filename, asNumpy=True):
  730. """Read all images from an SWF (shockwave flash) file. Returns a list
  731. of numpy arrays, or, if asNumpy is false, a list if PIL images.
  732. Limitation: only read the PNG encoded images (not the JPG encoded ones).
  733. """
  734. # Check whether it exists
  735. if not os.path.isfile(filename):
  736. raise IOError("File not found: " + str(filename))
  737. # Check PIL
  738. if (not asNumpy) and (PIL is None):
  739. raise RuntimeError("Need PIL to return as PIL images.")
  740. # Check Numpy
  741. if np is None:
  742. raise RuntimeError("Need Numpy to read SWF files.")
  743. # Init images
  744. images = []
  745. # Open file and read all
  746. fp = open(filename, "rb")
  747. bb = fp.read()
  748. try:
  749. # Check opening tag
  750. tmp = bb[0:3].decode("ascii", "ignore")
  751. if tmp.upper() == "FWS":
  752. pass # ok
  753. elif tmp.upper() == "CWS":
  754. # Decompress movie
  755. bb = bb[:8] + zlib.decompress(bb[8:])
  756. else:
  757. raise IOError("Not a valid SWF file: " + str(filename))
  758. # Set filepointer at first tag (skipping framesize RECT and two uin16's
  759. i = 8
  760. nbits = bitsToInt(bb[i : i + 1], 5) # skip FrameSize
  761. nbits = 5 + nbits * 4
  762. Lrect = nbits / 8.0
  763. if Lrect % 1:
  764. Lrect += 1
  765. Lrect = int(Lrect)
  766. i += Lrect + 4
  767. # Iterate over the tags
  768. counter = 0
  769. while True:
  770. counter += 1
  771. # Get tag header
  772. head = bb[i : i + 6]
  773. if not head:
  774. break # Done (we missed end tag)
  775. # Determine type and length
  776. T, L1, L2 = getTypeAndLen(head)
  777. if not L2:
  778. print("Invalid tag length, could not proceed")
  779. break
  780. # print(T, L2)
  781. # Read image if we can
  782. if T in [20, 36]:
  783. im = _readPixels(bb, i + 6, T, L1)
  784. if im is not None:
  785. images.append(im)
  786. elif T in [6, 21, 35, 90]:
  787. print("Ignoring JPEG image: cannot read JPEG.")
  788. else:
  789. pass # Not an image tag
  790. # Detect end tag
  791. if T == 0:
  792. break
  793. # Next tag!
  794. i += L2
  795. finally:
  796. fp.close()
  797. # Convert to normal PIL images if needed
  798. if not asNumpy:
  799. images2 = images
  800. images = []
  801. for im in images2:
  802. images.append(PIL.Image.fromarray(im))
  803. # Done
  804. return images