从imagecopyresampled获取流

时间:2015-11-09 01:21:17

标签: php php-gd

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

1 个答案:

答案 0 :(得分:1)

您应该使用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