2015-11-09 47 views
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 
+0

我怀疑'图片资源标识符'是'流资源'。您希望以何种格式获得图像? PNG,JPEG,GIF? –

+0

您也已经销毁该图像资源。 –

+0

@gre_gor请参阅我的** Update 1 **。另外它假设我应该给出格式? –

回答

0

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