images2swf.py 29 KB

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