Gif.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2015 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: yunwuxin <448901948@qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\image\gif;
  12. class Gif
  13. {
  14. /**
  15. * GIF帧列表
  16. *
  17. * @var array
  18. */
  19. private $frames = [];
  20. /**
  21. * 每帧等待时间列表
  22. *
  23. * @var array
  24. */
  25. private $delays = [];
  26. /**
  27. * 构造方法,用于解码GIF图片
  28. *
  29. * @param string $src GIF图片数据
  30. * @param string $mod 图片数据类型
  31. * @throws \Exception
  32. */
  33. public function __construct($src = null, $mod = 'url')
  34. {
  35. if (!is_null($src)) {
  36. if ('url' == $mod && is_file($src)) {
  37. $src = file_get_contents($src);
  38. }
  39. /* 解码GIF图片 */
  40. try {
  41. $de = new Decoder($src);
  42. $this->frames = $de->getFrames();
  43. $this->delays = $de->getDelays();
  44. } catch (\Exception $e) {
  45. throw new \Exception("解码GIF图片出错");
  46. }
  47. }
  48. }
  49. /**
  50. * 设置或获取当前帧的数据
  51. *
  52. * @param string $stream 二进制数据流
  53. * @return mixed 获取到的数据
  54. */
  55. public function image($stream = null)
  56. {
  57. if (is_null($stream)) {
  58. $current = current($this->frames);
  59. return false === $current ? reset($this->frames) : $current;
  60. }
  61. $this->frames[key($this->frames)] = $stream;
  62. }
  63. /**
  64. * 将当前帧移动到下一帧
  65. *
  66. * @return string 当前帧数据
  67. */
  68. public function nextImage()
  69. {
  70. return next($this->frames);
  71. }
  72. /**
  73. * 编码并保存当前GIF图片
  74. *
  75. * @param string $pathname 图片名称
  76. */
  77. public function save($pathname)
  78. {
  79. $gif = new Encoder($this->frames, $this->delays, 0, 2, 0, 0, 0, 'bin');
  80. file_put_contents($pathname, $gif->getAnimation());
  81. }
  82. }