---
title: "PHP图象处理的函数imagecreatefromstring的问题"
author: "bardo"
date: "2010-05-04T22:19:41Z"
tags: []
categories: ["编程语言"]
slug: "php-imagecreatefromstring"
draft: false
lastmod: "2010-05-04T22:19:41Z"
id: 659072
url: "https://bardo.iteye.com/blog/659072"
---

PHP图象处理的函数imagecreatefromstring，可以直接将二进制图像字串（数据流）创建成图像资源。

因而，使用此函数免去了大量的文件IO。

比如，我们可以在必要时用imagegd2或imagegif等函数输出。但我们可以控制其输出到我们所要的变量中。如同以下代码：

```php

 function _image_to_buffer($resource){ 
  ob_start();
  imagegif($resource);
  $output_buf= ob_get_contents();
  ob_end_clean(); 
  return $output_buf;
 } 

```


然后，再用imagecreatefromstring去做进一步的操作。也许你会说，这可能没有这样的必要。但是，对于GIF动画的处理，比如，完成功能如：resize animatedt gif，water mark  animatedt gif等，就有可能必须要这样做。

但很奇怪的是：imagecreatefromstring，当图象小于GIF的实际逻辑屏幕定义，并且 image left possition和image top possition不为0时，imagecreatefromstring会将此二者改为0，同时，图象不再是实际逻辑屏幕定义长与宽，而是image descroptor中的长与宽。不太清楚，这是否属于PHP图像处理函数的一个BUG。

并且，很让人遗憾的是 imagemagik 针对GIF动画制作缩略图时，也有这样的问题。 这样，原来的动画就出问题了。本来该在下面动的物体跑到了左上角。

因此，对于imagecreatefromstring，必须要另想办法，来改变这一个问题。

```php

  $data = $this->get_frame_data($i); 
  $tmp_im = imagecreatefromstring ($data);
  $w= imagesx($tmp_im);
  $h= imagesy($tmp_im);
  $left_pos = $this->_word_to_int($this->gif_frames[$i]['img_dsc']['img_left_pos']);
  $top_pos = $this->_word_to_int($this->gif_frames[$i]['img_dsc']['img_top_pos']);
  $img_w = $this->_word_to_int($this->gif_frames[$i]['img_dsc']['img_w']);
  $img_h = $this->_word_to_int($this->gif_frames[$i]['img_dsc']['img_h']);

  if (($w< $this->gif_lsd['ls_w'])||($h<$this->gif_lsd['ls_h'])){
   $fra_im=imagecreatetruecolor($this->gif_lsd['ls_w'],$this->gif_lsd['ls_h']);
   if ($this->gif_frames[$i]['grph_ctrl_ext']['transparent']==1){    
    $color = $this->gif_gct['data'][$this->gif_frames[$i]['grph_ctrl_ext']['transparent_clr_idx']];
    imagepalettecopy($fra_im,$tmp_im);
    imagecolortransparent($fra_im,$color); 
    imagefilledrectangle($fra_im,0,0,$this->gif_lsd['ls_w'],$this->gif_lsd['ls_h'],$color);
   }
   imagecopy ($fra_im, $tmp_im, $left_pos, $top_pos, 0, 0, $img_w, $img_h);
  }   
  else 
   $fra_im=$tmp_im; 

```


这样，再用 $fra_im就正确了。