images2swf.py 30 KB

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