images2swf.py 29 KB

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