images2swf.py 29 KB

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