php
PHP - 작은 이미지로 변환하여 MYSQL에 저장하기
이미지를 작은 이미지로 변환한 문자열을 Mysql에 저장하는 방법을 소개합니다. 큰 이미지를 저장하기에는 무리가 있으나 작은 이미지로 변환한 문자열을 Mysql 에 저장하면 속도 면에서 오히려 더 빠를 수 있습니다. 먼저 Mysql 테이블을 만듭니다.
CREATE TABLE `images` (
`id` int(10) NOT NULL,
`type` char(4) NOT NULL,
`thumbs` blob NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
<?php
function Thumbnail_String($string, $user_width=86, $user_height=null)
{
ob_start();
ob_flush();
flush();
$im = imagecreatefromstring( $string );
$orig_width = imagesx($im);
$orig_height = imagesy($im);
if($orig_width >= $user_width)
{
if(strlen($user_height) === 0)
{
$user_height = @round($orig_height*($user_width/$orig_width));
}
}
else
{
$user_width = $orig_width;
$user_height = $orig_height;
}
$im_new = imagecreatetruecolor( $user_width, $user_height );
imagecopyresampled($im_new, $im, 0, 0, 0, 0,
$user_width, $user_height, $orig_width, $orig_height);
imagepng($im_new);
imagedestroy($im);
imagedestroy($im_new);
$data = ob_get_contents();
ob_end_clean();
return $data;
}
// 이미지를 sql에 저장하기
$file = file_get_contents($_FILES['userfile']['tmp_name']);
unlink($_FILES['userfile']['tmp_name']);
$data = Thumbnail_String($file, 50);
mysqli_query($link,
"insert into from tbname VALUES('1', 'png', '".$data."');");
// sql에 저장된 이미지를 불러오기
$result = mysqli_query($link, "select thumbs from tbname WHERE id=1;");
$row = mysqli_fetch_array($result, MYSQLI_NUM);
echo "<img src='data:image/gif;base64, ".base64_encode($row[0])."'>";
?>
0 댓글