Gif.php 1.8 KB

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