images2swf.py 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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),
  461. dtype=np.uint8) * 255
  462. for i in range(3):
  463. tmp[:, :, i + 1] = im[:, :, i]
  464. if im.shape[2] == 4:
  465. tmp[:, :, 0] = im[:, :, 3] # swap channel where alpha is in
  466. else:
  467. raise ValueError("Invalid shape to be an image.")
  468. elif len(im.shape) == 2:
  469. tmp = np.ones((im.shape[0], im.shape[1], 4), dtype=np.uint8)*255
  470. for i in range(3):
  471. tmp[:, :, i + 1] = im[:, :]
  472. else:
  473. raise ValueError("Invalid shape to be an image.")
  474. # we changed the image to uint8 4 channels.
  475. # now compress!
  476. self._data = zlib.compress(tmp.tostring(), zlib.DEFLATED)
  477. self.imshape = im.shape
  478. def ProcessTag(self):
  479. # build tag
  480. bb = binary_type()
  481. bb += intToUint16(self.id) # CharacterID
  482. bb += intToUint8(5) # BitmapFormat
  483. bb += intToUint16(self.imshape[1]) # BitmapWidth
  484. bb += intToUint16(self.imshape[0]) # BitmapHeight
  485. bb += self._data # ZlibBitmapData
  486. self.bytes = bb
  487. class PlaceObjectTag(ControlTag):
  488. def __init__(self, depth, idToPlace=None, xy=(0, 0), move=False):
  489. ControlTag.__init__(self)
  490. self.tagtype = 26
  491. self.depth = depth
  492. self.idToPlace = idToPlace
  493. self.xy = xy
  494. self.move = move
  495. def ProcessTag(self):
  496. # retrieve stuff
  497. depth = self.depth
  498. xy = self.xy
  499. id = self.idToPlace
  500. # build PlaceObject2
  501. bb = binary_type()
  502. if self.move:
  503. bb += '\x07'.encode('ascii')
  504. else:
  505. bb += '\x06'.encode('ascii') # (8 bit flags): 4:matrix, 2:character, 1:move
  506. bb += intToUint16(depth) # Depth
  507. bb += intToUint16(id) # character id
  508. bb += self.MakeMatrixRecord(trans_xy=xy).ToBytes() # MATRIX record
  509. self.bytes = bb
  510. class ShapeTag(DefinitionTag):
  511. def __init__(self, bitmapId, xy, wh):
  512. DefinitionTag.__init__(self)
  513. self.tagtype = 2
  514. self.bitmapId = bitmapId
  515. self.xy = xy
  516. self.wh = wh
  517. def ProcessTag(self):
  518. """ Returns a defineshape tag. with a bitmap fill """
  519. bb = binary_type()
  520. bb += intToUint16(self.id)
  521. xy, wh = self.xy, self.wh
  522. tmp = self.MakeRectRecord(xy[0], wh[0], xy[1], wh[1]) # ShapeBounds
  523. bb += tmp.ToBytes()
  524. # make SHAPEWITHSTYLE structure
  525. # first entry: FILLSTYLEARRAY with in it a single fill style
  526. bb += intToUint8(1) # FillStyleCount
  527. bb += '\x41'.encode('ascii') # FillStyleType (0x41 or 0x43, latter is non-smoothed)
  528. bb += intToUint16(self.bitmapId) # BitmapId
  529. #bb += '\x00' # BitmapMatrix (empty matrix with leftover bits filled)
  530. bb += self.MakeMatrixRecord(scale_xy=(20, 20)).ToBytes()
  531. # # first entry: FILLSTYLEARRAY with in it a single fill style
  532. # bb += intToUint8(1) # FillStyleCount
  533. # bb += '\x00' # solid fill
  534. # bb += '\x00\x00\xff' # color
  535. # second entry: LINESTYLEARRAY with a single line style
  536. bb += intToUint8(0) # LineStyleCount
  537. #bb += intToUint16(0*20) # Width
  538. #bb += '\x00\xff\x00' # Color
  539. # third and fourth entry: NumFillBits and NumLineBits (4 bits each)
  540. # I each give them four bits, so 16 styles possible.
  541. bb += '\x44'.encode('ascii')
  542. self.bytes = bb
  543. # last entries: SHAPERECORDs ... (individual shape records not aligned)
  544. # STYLECHANGERECORD
  545. bits = BitArray()
  546. bits += self.MakeStyleChangeRecord(0, 1, moveTo=(self.wh[0],
  547. self.wh[1]))
  548. # STRAIGHTEDGERECORD 4x
  549. bits += self.MakeStraightEdgeRecord(-self.wh[0], 0)
  550. bits += self.MakeStraightEdgeRecord(0, -self.wh[1])
  551. bits += self.MakeStraightEdgeRecord(self.wh[0], 0)
  552. bits += self.MakeStraightEdgeRecord(0, self.wh[1])
  553. # ENDSHAPRECORD
  554. bits += self.MakeEndShapeRecord()
  555. self.bytes += bits.ToBytes()
  556. # done
  557. #self.bytes = bb
  558. def MakeStyleChangeRecord(self, lineStyle=None, fillStyle=None,
  559. moveTo=None):
  560. # first 6 flags
  561. # Note that we use FillStyle1. If we don't flash (at least 8) does not
  562. # recognize the frames properly when importing to library.
  563. bits = BitArray()
  564. bits += '0' # TypeFlag (not an edge record)
  565. bits += '0' # StateNewStyles (only for DefineShape2 and Defineshape3)
  566. if lineStyle:
  567. bits += '1' # StateLineStyle
  568. else:
  569. bits += '0'
  570. if fillStyle:
  571. bits += '1' # StateFillStyle1
  572. else:
  573. bits += '0'
  574. bits += '0' # StateFillStyle0
  575. if moveTo:
  576. bits += '1' # StateMoveTo
  577. else:
  578. bits += '0'
  579. # give information
  580. # todo: nbits for fillStyle and lineStyle is hard coded.
  581. if moveTo:
  582. bits += twitsToBits([moveTo[0], moveTo[1]])
  583. if fillStyle:
  584. bits += intToBits(fillStyle, 4)
  585. if lineStyle:
  586. bits += intToBits(lineStyle, 4)
  587. return bits
  588. #return bitsToBytes(bits)
  589. def MakeStraightEdgeRecord(self, *dxdy):
  590. if len(dxdy) == 1:
  591. dxdy = dxdy[0]
  592. # determine required number of bits
  593. xbits = signedIntToBits(dxdy[0] * 20)
  594. ybits = signedIntToBits(dxdy[1] * 20)
  595. nbits = max([len(xbits), len(ybits)])
  596. bits = BitArray()
  597. bits += '11' # TypeFlag and StraightFlag
  598. bits += intToBits(nbits-2, 4)
  599. bits += '1' # GeneralLineFlag
  600. bits += signedIntToBits(dxdy[0] * 20, nbits)
  601. bits += signedIntToBits(dxdy[1] * 20, nbits)
  602. # note: I do not make use of vertical/horizontal only lines...
  603. return bits
  604. #return bitsToBytes(bits)
  605. def MakeEndShapeRecord(self):
  606. bits = BitArray()
  607. bits += "0" # TypeFlag: no edge
  608. bits += "0"*5 # EndOfShape
  609. return bits
  610. #return bitsToBytes(bits)
  611. ## Last few functions
  612. def buildFile(fp, taglist, nframes=1, framesize=(500, 500), fps=10, version=8):
  613. """ Give the given file (as bytes) a header. """
  614. # compose header
  615. bb = binary_type()
  616. bb += 'F'.encode('ascii') # uncompressed
  617. bb += 'WS'.encode('ascii') # signature bytes
  618. bb += intToUint8(version) # version
  619. bb += '0000'.encode('ascii') # FileLength (leave open for now)
  620. bb += Tag().MakeRectRecord(0, framesize[0], 0, framesize[1]).ToBytes()
  621. bb += intToUint8(0) + intToUint8(fps) # FrameRate
  622. bb += intToUint16(nframes)
  623. fp.write(bb)
  624. # produce all tags
  625. for tag in taglist:
  626. fp.write(tag.GetTag())
  627. # finish with end tag
  628. fp.write('\x00\x00'.encode('ascii'))
  629. # set size
  630. sze = fp.tell()
  631. fp.seek(4)
  632. fp.write(intToUint32(sze))
  633. def writeSwf(filename, images, duration=0.1, repeat=True):
  634. """Write an swf-file from the specified images. If repeat is False,
  635. the movie is finished with a stop action. Duration may also
  636. be a list with durations for each frame (note that the duration
  637. for each frame is always an integer amount of the minimum duration.)
  638. Images should be a list consisting of PIL images or numpy arrays.
  639. The latter should be between 0 and 255 for integer types, and
  640. between 0 and 1 for float types.
  641. """
  642. # Check Numpy
  643. if np is None:
  644. raise RuntimeError("Need Numpy to write an SWF file.")
  645. # Check images (make all Numpy)
  646. images2 = []
  647. images = checkImages(images)
  648. if not images:
  649. raise ValueError("Image list is empty!")
  650. for im in images:
  651. if PIL and isinstance(im, PIL.Image.Image):
  652. if im.mode == 'P':
  653. im = im.convert()
  654. im = np.asarray(im)
  655. if len(im.shape) == 0:
  656. raise MemoryError("Too little memory to convert PIL image to array")
  657. images2.append(im)
  658. # Init
  659. taglist = [FileAttributesTag(), SetBackgroundTag(0, 0, 0)]
  660. # Check duration
  661. if hasattr(duration, '__len__'):
  662. if len(duration) == len(images2):
  663. duration = [d for d in duration]
  664. else:
  665. raise ValueError("len(duration) doesn't match amount of images.")
  666. else:
  667. duration = [duration for im in images2]
  668. # Build delays list
  669. minDuration = float(min(duration))
  670. delays = [round(d/minDuration) for d in duration]
  671. delays = [max(1, int(d)) for d in delays]
  672. # Get FPS
  673. fps = 1.0/minDuration
  674. # Produce series of tags for each image
  675. nframes = 0
  676. for im in images2:
  677. bm = BitmapTag(im)
  678. wh = (im.shape[1], im.shape[0])
  679. sh = ShapeTag(bm.id, (0, 0), wh)
  680. po = PlaceObjectTag(1, sh.id, move=nframes > 0)
  681. taglist.extend([bm, sh, po])
  682. for i in range(delays[nframes]):
  683. taglist.append(ShowFrameTag())
  684. nframes += 1
  685. if not repeat:
  686. taglist.append(DoActionTag('stop'))
  687. # Build file
  688. fp = open(filename, 'wb')
  689. try:
  690. buildFile(fp, taglist, nframes=nframes, framesize=wh, fps=fps)
  691. except Exception:
  692. raise
  693. finally:
  694. fp.close()
  695. def _readPixels(bb, i, tagType, L1):
  696. """ With pf's seed after the recordheader, reads the pixeldata.
  697. """
  698. # Check Numpy
  699. if np is None:
  700. raise RuntimeError("Need Numpy to read an SWF file.")
  701. # Get info
  702. charId = bb[i:i + 2]; i += 2
  703. format = ord(bb[i:i + 1]); i += 1
  704. width = bitsToInt(bb[i:i + 2], 16); i += 2
  705. height = bitsToInt(bb[i:i + 2], 16); i += 2
  706. # If we can, get pixeldata and make nunmpy array
  707. if format != 5:
  708. print("Can only read 24bit or 32bit RGB(A) lossless images.")
  709. else:
  710. # Read byte data
  711. offset = 2 + 1 + 2 + 2 # all the info bits
  712. bb2 = bb[i:i+(L1-offset)]
  713. # Decompress and make numpy array
  714. data = zlib.decompress(bb2)
  715. a = np.frombuffer(data, dtype=np.uint8)
  716. # Set shape
  717. if tagType == 20:
  718. # DefineBitsLossless - RGB data
  719. try:
  720. a.shape = height, width, 3
  721. except Exception:
  722. # Byte align stuff might cause troubles
  723. print("Cannot read image due to byte alignment")
  724. if tagType == 36:
  725. # DefineBitsLossless2 - ARGB data
  726. a.shape = height, width, 4
  727. # Swap alpha channel to make RGBA
  728. b = a
  729. a = np.zeros_like(a)
  730. a[:, :, 0] = b[:, :, 1]
  731. a[:, :, 1] = b[:, :, 2]
  732. a[:, :, 2] = b[:, :, 3]
  733. a[:, :, 3] = b[:, :, 0]
  734. return a
  735. def readSwf(filename, asNumpy=True):
  736. """Read all images from an SWF (shockwave flash) file. Returns a list
  737. of numpy arrays, or, if asNumpy is false, a list if PIL images.
  738. Limitation: only read the PNG encoded images (not the JPG encoded ones).
  739. """
  740. # Check whether it exists
  741. if not os.path.isfile(filename):
  742. raise IOError('File not found: '+str(filename))
  743. # Check PIL
  744. if (not asNumpy) and (PIL is None):
  745. raise RuntimeError("Need PIL to return as PIL images.")
  746. # Check Numpy
  747. if np is None:
  748. raise RuntimeError("Need Numpy to read SWF files.")
  749. # Init images
  750. images = []
  751. # Open file and read all
  752. fp = open(filename, 'rb')
  753. bb = fp.read()
  754. try:
  755. # Check opening tag
  756. tmp = bb[0:3].decode('ascii', 'ignore')
  757. if tmp.upper() == 'FWS':
  758. pass # ok
  759. elif tmp.upper() == 'CWS':
  760. # Decompress movie
  761. bb = bb[:8] + zlib.decompress(bb[8:])
  762. else:
  763. raise IOError('Not a valid SWF file: ' + str(filename))
  764. # Set filepointer at first tag (skipping framesize RECT and two uin16's
  765. i = 8
  766. nbits = bitsToInt(bb[i: i + 1], 5) # skip FrameSize
  767. nbits = 5 + nbits * 4
  768. Lrect = nbits / 8.0
  769. if Lrect % 1:
  770. Lrect += 1
  771. Lrect = int(Lrect)
  772. i += Lrect+4
  773. # Iterate over the tags
  774. counter = 0
  775. while True:
  776. counter += 1
  777. # Get tag header
  778. head = bb[i:i+6]
  779. if not head:
  780. break # Done (we missed end tag)
  781. # Determine type and length
  782. T, L1, L2 = getTypeAndLen(head)
  783. if not L2:
  784. print('Invalid tag length, could not proceed')
  785. break
  786. #print(T, L2)
  787. # Read image if we can
  788. if T in [20, 36]:
  789. im = _readPixels(bb, i+6, T, L1)
  790. if im is not None:
  791. images.append(im)
  792. elif T in [6, 21, 35, 90]:
  793. print('Ignoring JPEG image: cannot read JPEG.')
  794. else:
  795. pass # Not an image tag
  796. # Detect end tag
  797. if T == 0:
  798. break
  799. # Next tag!
  800. i += L2
  801. finally:
  802. fp.close()
  803. # Convert to normal PIL images if needed
  804. if not asNumpy:
  805. images2 = images
  806. images = []
  807. for im in images2:
  808. images.append(PIL.Image.fromarray(im))
  809. # Done
  810. return images