/*
二进制数据流生成缩略图
@$data 二进制图像数据流
@$mimetype 图像类型
@$thumbnailHeight 缩略图高度
@$thumbnailWidth 缩略图宽度
return 缩略图的二进制数据流
*/
function _render_thumbnail($data, $mimetype,$thumbnailHeight=60,$thumbnailWidth=100)
{
//echo $data;
// file is not an image
if ($mimetype !== 'image/jpeg' &&
$mimetype !== 'image/pjpeg' &&
$mimetype !== 'image/gif' &&
$mimetype !== 'image/png')
{
throw new Exception('Unsupported file type.');
}
$ret = '';
$imageType = substr($mimetype, 6);
$image = imagecreatefromstring($data);
$width = imagesx($image);
$height = imagesy($image);
// decrease image size if height exceeds thumbnailHeight
if ($height > $thumbnailHeight)
{
$factor = $thumbnailHeight / $height;
$targetWidth = round($factor * $width);
$imageNew = imagecreatetruecolor($targetWidth, $thumbnailHeight);
imagecopyresampled($imageNew, $image, 0, 0, 0, 0, $targetWidth, $thumbnailHeight, $width, $height);
}
// otherwise, check for width
else if ($width > $thumbnailWidth)
{
$factor = $thumbnailWidth / $width;
$targetHeight = round($factor * $width);
$imageNew = imagecreatetruecolor($thumbnailWidth, $targetHeight);
imagecopyresampled($imageNew, $image, 0, 0, 0, 0, $thumbnailWidth, $targetHeight, $width, $height);
}
// if the image is small enough, we take it as-is
else
{
return $data;
}
// store new image data in a variable
ob_start();
switch ($imageType)
{
case 'jpeg' : imagejpeg($imageNew, null, 100);
break;
case 'pjpeg' : imagejpeg($imageNew, null, 100);
break;
case 'gif' : imagegif($imageNew);
break;
case 'png' : imagepng($imageNew, null, 0);
break;
}
imagedestroy($imageNew);
$ret = ob_get_clean();
return $ret;
}
?>
主要是 imagecreatefromstring 函数的使用。