图像调整大小使用PHP图像魔术师

时间:2013-06-30 18:30:48

标签: php html

我正在尝试使用php-image-magician显示上传的图像以及不同大小的文本水印而不保存图像。

以下是代码:

<?php

$errors = array();

function mimeValidator($imagefile)
{
$imageInfo = getimagesize($imagefile);
$allowedMimes = array('image/jpg', 'image/jpeg', 'image/png');

if(!in_array($imageInfo['mime'], $allowedMimes))
$errors[] = "Only jpg and png images are supported";
}

function renderImage($imageSource, $watermark, $fontSize, $font)
{
$imageInfo = getimagesize($imageSource);
list($width,$height) = getimagesize($imageSource);

if($imageInfo['mime'] == 'image/jpg' || $imageInfo['mime'] == 'image/jpeg')
$imageSource = imagecreatefromjpeg($imageSource);
elseif($imageInfo['mime'] == 'image/png')
$imageSource = imagecreatefrompng($imageSource);

$image = imagecreatetruecolor($width, $height);
$blue = imagecolorallocate($image, 79, 166, 185);
$text = imagettftext($imageSource, $fontSize, 0, 20, ($height-20), $blue, $font,      $watermark);

ob_start();
imagejpeg($imageSource);
$image = ob_get_contents();
ob_end_clean();

return base64_encode($image);
}

?><html>
<head>
<title>
image Watermark and resize
</title>

<style type="text/css">
body{ width:800px; margin: 15px auto; padding:0px; font-family: arial}    

</style>
</head>
<body>
<form name="imageUpload" id="imageUpload" method="post" enctype="multipart/form-data" >
<fieldset>
<legend>Image text watermark</legend>
Text: <input type="text" name="text" id="text"/><br />
Image: <input type="file" name="image" id="image"/><br />
<input type="submit" name="submit" id="createmark" value="Submit" />
</fieldset>   
<?php

if(isset($_POST['submit']))
{
if($_POST['text'] == '')
$errors[] = "Text is too short";

if($_FILES['image']['tmp_name'] == '')
$errors[] = "Please upload a image";
else
mimeValidator($_FILES['image']['tmp_name']);

if(count($errors) == 0)
                {
include('php-image-magician/php_image_magician.php');

$magicianObj = new imageLib($_FILES["image"]["tmp_name"]);
$magicianObj -> resizeImage(100, 200);
$magicianObj -> saveImage($imagename);
echo "<img src=\"data:image/gif;base64," . renderImage($_FILES["image"]["tmp_name"],  $_POST['text'], 30, "./arial.ttf") . "\" />";
}
else
{
echo "<ul>";

foreach($errors as $error)
echo "<li>{$error}</li>";

echo "</ul>";
}

}
?>
</form>
</body>
</html>

我收到错误“文件C:\ xampp \ tmp \ php9E3D.tmp缺失或无效” 我是新手。请帮帮我。

1 个答案:

答案 0 :(得分:1)

我从未使用过php-image-magician,所以以下内容很可能是虚假信息。

从我看到的内容:

$magicianObj = new imageLib($_FILES["image"]["tmp_name"]);

在内部,imageLib调用openImage,后者又会执行以下操作: 1)它检查文件是否确实存在 2)它检查扩展并使用正确的imagecreatefrom_ _ _函数。

这是你的问题开始的地方。当您将文件上传到您的网络服务器时,它们会以临时文件名保存(在您的示例中,“php9E3D.tmp”)。此扩展名(.tmp)不在php-image-magician允许的扩展名列表中(.jpg,.jpeg,.gif,.png,.bmp,.psd)。因此,内部image变量设置为false,整个库将无法工作。

您有几种方法可以解决此问题:

1)重写php-image-magician(特别是openImage),但不建议这样做。

2)使用move_uploaded_file重命名您上传的文件,参见示例#2 here

3)摆脱对php-image-magician的依赖,并使用PHP内部函数(imagescale和朋友,你已经创建了一个在renderImage函数中使用的图像资源)

希望这有帮助。

相关问题