Мне нужно создать эскизы из blob и сохранить в базе данных, поэтому у меня есть следующая функция
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
Вы должны использовать imagejpeg()
для вывода ваших данных изображения, а затем захватить его с помощью ob_start()
и ob_get_clean()
.
function createSquareImage($imgResource, $square_size = 96) {
// other code
ob_start();
imagejpeg($squareImg);
$imageData = ob_get_clean();
imagedestroy($imgResource);
imagedestroy($thumbImg);
imagedestroy($squareImg);
return $imageData;
}
Это вернет данные JPEG вашего изображения, и вам не нужно будет использовать stream_get_contents
.
image resource identifier
являетсяstream resource
. В каком формате вы ожидаете получить изображение? PNG, JPEG, GIF?