从imagecopy重新采样中获取流


Get stream from imagecopyresampled

我需要从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