2012-02-25 24 views
1

我有一个图像文件存储到数据库作为blob(代码中显示)。一旦调整到80 * 80(缩略图),我需要将它存储到其他数据库。我已调整大小并将其保存为文件,但无法将调整大小的图像存储到数据库中。我怎样才能做到这一点?如何在PHP上调整图像文件的大小?

//resize image and save 
include('MyImage.php'); 
$image = new MyImage(); 
$image->load($tmpName); 
$image->resize(80,80); 
$image->save('thumbnail.jpg'); 


//storing original image onto database 
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) 
{ 
$fileName = $_FILES['userfile']['name']; 
$tmpName = $_FILES['userfile']['tmp_name']; 
$fileSize = $_FILES['userfile']['size']; 
$fileType = $_FILES['userfile']['type']; 

$fp  = fopen($tmpName, 'r'); 
$content = fread($fp, filesize($tmpName)); 
$content = addslashes($content); 
fclose($fp); 

if(!get_magic_quotes_gpc()) 
    { 
    $fileName = addslashes($fileName); 
    } 

$query = "INSERT INTO image_tbl (name, size, type, content)". 
      "VALUES ('$fileName', '$fileSize', '$fileType', '$content')"; 
mysql_query($query) or die('Error, query failed'); 
} 
+0

从过去在数据库中存储图像的人,我不认为这是一个好主意。 – ppp 2012-02-25 22:48:03

+2

1.完全缺乏sql注入保护(没有,addslashes不是保护)。 2.完全没有验证上传的成功。 3.明显缺乏对'file_get_contents()'的认识。 4.在定义之前使用变量($ tmpname)。 – 2012-02-25 23:16:16

+0

@anpel你是说图像存储在数据库不是一个好主意吗? – 2012-02-25 23:32:28

回答

2

到你的答案的直接问题是

//This goes after the frist block, after "$image->save('thumbnail.jpg');" 

$fileSize=filesize('thumbnail.jpg') 
$fp  = fopen('thumbnail.jpg', 'rb'); 
$content = fread($fp, $fileSize); 
$content = addslashes($content); 
fclose($fp); 

$query = "INSERT INTO image_tbl (name, size, type, content)". 
      "VALUES ('thumbnail.jpg', '$fileSize', 'image/jpeg', '$content')"; 
mysql_query($query) or die('Error, query failed'); 

你可能会认识到代码的某些元素:-)

但请相信我,你不想这样:

  • 在数据库中存储BLOB,即数据库不明白是一个坏主意
  • 使用字符串和addslashes实现它是非常接近最糟糕的情况可能:您将图像读取到由大约50%unprintables组成的字符串中,反斜杠,将其传输到数据库,然后在数据库中进行解压缩和解析。使用准备好的语句与参数(如果你真的想保存在数据库中的图像)
0

试试这个:

$file = $path_you_saved_image."/".$your_image_name; 
$handle = fopen($file , "rb"); 
$img = fread($handle , filesize($file)); 
$img = base64_encode($img); 
$query = "insert into images (image) values ('$img')"; 
mysql_query($query) or die(mysql_error()); 
0

你的代码表明您已经保存了调整后的图像。现在打开这个调整大小的图像'thumbnail.jpg'并处理它,对它进行编码并保存。