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