使用imagecreatefromjpeg和imagejpeg时出现问题

时间:2009-12-22 19:24:07

标签: php

根据给我的任务,我试图看到php的以下两个函数对图像文件的影响 1. imagecreatefromjpeg 2. imagejpeg

我使用html上传文件,然后我的php代码如下所示:

 <?php

 try{
   if(!$image=imagecreatefromjpeg('zee1.jpg')){
      throw new Exception('Error loading image');
   }
   // create text color for jpg image
   if(!$textColor=imagecolorallocate($image,0,255,0)){
      throw new Exception('Error creating text color');
   }
   // include text string into jpg image
   if(!$text=imagestring($image,5,10,90,'This is a sample text
string.',$textColor)){
      throw new Exception('Error creating image text');
   }
   header("Content-type:image/jpeg");
   // display image
   imagejpeg($image, 'zee1After.jpg');
   // free up memory
   imagedestroy($image);
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

    ?>

但是当我这样做时,我得到以下输出:

致命错误:第3行的C:\ Users \ zee \ Documents \ Flex Builder 3 \ CLOUD \ bin-debug \ upload_file.php中允许的内存大小为33554432字节(尝试分配10368字节)

原始图像的大小为:5,136 KB运行php后出现上述错误。

但是,如果我尝试其他大小的图像:2,752 KB它可以工作..

有人可以帮我解决这个问题。 Zeeshan

4 个答案:

答案 0 :(得分:5)

首先删除header("Content-type:image/jpeg");行,因为你正在使用imagejpeg()函数的filename参数,所以它什么也没做。

其次,为避免内存问题,您应该更改内存限制,例如:

ini_set('memory_limit', -1);

应解决您的问题(将其放在文件的开头)。

要恢复原始内存限制,您可以在文件末尾添加以下行:

ini_restore('memory_limit');

整个脚本看起来像这样:

<?php

ini_set('memory_limit', -1);

try 
{
    if (!$image = imagecreatefromjpeg('zee1.jpg'))
    {
        throw new Exception('Error loading image');
    }

    // create text color for jpg image
    if (!$textColor = imagecolorallocate($image, 0, 255, 0))
    {
        throw new Exception('Error creating text color');
    }

    // include text string into jpg image
    if (!$text = imagestring($image, 5, 10, 90, 'This is a sample text string.', $textColor))
    {
        throw new Exception('Error creating image text');
    }

    // display image
    imagejpeg($image, 'zee1After.jpg');

    // free up memory
    imagedestroy($image);
}

catch (Exception $e)
{
    echo $e->getMessage();
    exit();
}

ini_restore('memory_limit');

?>

答案 1 :(得分:0)

您正在请求文件的名称,而不是文件的路径。尝试:

$imgname = $_FILES["file"]["tmp_name"];

答案 2 :(得分:0)

  

警告:无法修改标头   信息 - 已由

发送的标头

确认在打开PHP标记之前不是任何字符;这是获取该错误消息的原因。如果您没有看到任何字符,则可能是文件以BOM序列开头,该序列是UTF文件中的字符序列,允许了解文件是以UTF-8,UTF-16 LE还是UTF编码-16 BE。

答案 3 :(得分:0)

这是因为您通过echo输出文本。标题无法再次发送,因为它们已经发送以便发送您的文本。考虑输出缓冲。

See my response to a similar question

编辑:另外,请参阅史蒂夫关于在tmp_name数组中使用“$_FILES”索引的帖子。