1
我需要创建一个BLOB缩略图并存储在数据库中,所以我有以下功能获取流从imagecopyresampled
function createSquareImage($imgResource, $square_size = 96) {
// get width and height of original image
$originalWidth = imagesx($imgResource);
$originalHeight = imagesy($imgResource);
if ($originalWidth > $originalHeight) {
$thumbHeight = $square_size;
$thumbWidth = $thumbHeight * ($originalWidth/$originalHeight);
}
if ($originalHeight > $originalWidth) {
$thumbWidth = $square_size;
$thumbHeight = $thumbWidth * ($originalHeight/$originalWidth);
}
if ($originalHeight == $originalWidth) {
$thumbWidth = $square_size;
$thumbHeight = $square_size;
}
$thumbWidth = round($thumbWidth);
$thumbHeight = round($thumbHeight);
$thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
$squareImg = imagecreatetruecolor($square_size, $square_size);
imagecopyresampled($thumbImg, $imgResource, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $originalWidth, $originalHeight);
if ($thumbWidth > $thumbHeight) {
$difference = $thumbWidth - $thumbHeight;
$halfDifference = round($difference/2);
imagecopyresampled($squareImg, $thumbImg, 0 - $halfDifference + 1, 0, 0, 0, $square_size + $difference, $square_size, $thumbWidth, $thumbHeight);
}
if ($thumbHeight > $thumbWidth) {
$difference = $thumbHeight - $thumbWidth;
$half_difference = round($difference/2);
imagecopyresampled($squareImg, $thumbImg, 0, 0 - $half_difference + 1, 0, 0, $square_size, $square_size + $difference, $thumbWidth, $thumbHeight);
}
if ($thumbHeight == $thumbWidth) {
imagecopyresampled($squareImg, $thumbImg, 0, 0, 0, 0, $square_size, $square_size, $thumbWidth, $thumbHeight);
}
imagedestroy($imgResource);
imagedestroy($thumbImg);
imagedestroy($squareImg);
return $squareImg;
}
我的电话:
$imgBlob = imagecreatefromstring(base64_decode($image->getContent()));
$thumbResource = $this->createSquareImage($imgBlob, 100);
$thumbContent = stream_get_contents($thumbResource);
// Save the stream ($thumbContent) in database
但我得到的异常
Warning: stream_get_contents(): 38 is not a valid stream resource
我在做什么错?
更新1:
如果我删除线imagedestroy($squareImg);
我得到一个类似的异常消息:
Warning: stream_get_contents(): supplied resource is not a valid stream resource
我怀疑'图片资源标识符'是'流资源'。您希望以何种格式获得图像? PNG,JPEG,GIF? –
您也已经销毁该图像资源。 –
@gre_gor请参阅我的** Update 1 **。另外它假设我应该给出格式? –