使用gd进行图像裁剪然后上传到数据库但不调整大小

时间:2009-07-21 17:42:48

标签: php gd

我的代码基本上应该将图像裁剪为219px×127px并将图像保存到数据库中,但是我收到错误而无法弄明白。

<?php
if(isset($_POST['btnupload']) && $_FILES['imglogo']['size'] > 0) {


$tmpname = $_FILES['imglogo']['tmp_name'];
$imgsize = $security->secure($_FILES['imglogo']['size']);
$imgtype = $security->secure($_FILES['imglogo']['type']);
$school = $security->secure($_POST['school']);

//crop image
$canvas = imagecreatetruecolor(219,127);
$imgattrib = getimagesize($tmpname);
$source = imagecreatefromjpeg($tmpname);
imagecopyresized($canvas,$source,0,0,0,0,219,127,$imgattrib[0],$imgattrib[1]);

$handle = fopen($tmpname, "r");
$content = fread($handle, filesize($tmpname));
$content = addslashes($content);
fclose($handle);




$save = mysql_query("insert into tbl_school_preview  values(null,'$school','$content','$imgtype','$imgsize')") or die(mysql_error());
//header("Location: school-catalog.php?page=school_preview");
}
?>

我没有看到任何错误,但作物没有发生。我有什么不对吗?

[更新代码] 由于某些原因拇指不能保存,这是新的块。

if(isset($_POST['btnupload']) && $_FILES['imglogo']['size'] > 0) {

//$filename = $security->secure($_FILES['imgschool']['name']);
$tmpname = $_FILES['imglogo']['tmp_name'];
$imgsize = $security->secure($_FILES['imglogo']['size']);
$imgtype = $security->secure($_FILES['imglogo']['type']);
$school = $security->secure($_POST['school']);

//crop image
$canvas = imagecreatetruecolor(219,127);
$imgattrib = getimagesize($tmpname);
$source = imagecreatefromjpeg($tmpname);
imagecopyresized($canvas,$source,0,0,0,0,219,127,$imgattrib[0],$imgattrib[1]);



$newfile = imagejpeg($canvas,'thumb.jpg',100);

$handle = fopen($newtmpfile, "r");
$content = fread($newtmpfile, filesize($newtmpfile));
$content = addslashes($content);
fclose($handle);




$save = mysql_query("insert into tbl_school_preview values(null,'$school','$content','$imgtype','$imgsize')") or die(mysql_error());

3 个答案:

答案 0 :(得分:0)

您应该保存$ canvas的内容,而不是原始图像的内容。

使用imagepng将其输出到临时文件,或者直接输出流,然后您必须截取它。

ob_start();

imagepng($帆布);

$ out = ob_get_contents();

ob_end_clean();

答案 1 :(得分:0)

您不需要执行任何fopen / fwrite来保存图像。用以下内容替换所有内容:

$filename = '/path/to/desired/save/location.png'
imagepng($canvas, $filename);

你应该好好去。当您为其提供第二个参数时,imagepng函数将写入该文件。对于imagegif和imagejpeg也是如此。

答案 2 :(得分:0)

只有两个提示:

我首先不要将文件保存到文件系统..您可以使用ob_start()来获取文件的内容。

ob_start();
imagepng($canvas);
$imageString = ob_get_contents();
ob_end_clean();

$save = mysql_query("
    insert into tbl_school_preview    
    values(null,'$school',$imagestring,'$imgtype','$imgsize')
    ")or die(mysql_error());

还可以使用imagecopyresampled()来提高缩略图的质量。插入数据库时​​,请注意图像代码中的奇怪字符。