开发者

Resizing images - Symfony

I have a number of images that are sotred as blob data in my database. I am aware this isn't a good idea, but it's what I'm using.

I hav开发者_StackOverflowe following code in my Peer class:

public function getImagesPath()
{
  $file_srcs = false;
  $fp = $this->getPhoto->getBlobData();

  if ($fp !== null)
  {
      $file = stream_get_contents($fp);
      $file_srcs = '/uploads/gallery/'.$this->getId().'.jpg';

  }
return $file_srcs;

}

I then call this in my template, like so:

            $path = $item->getImagesPath();
            if ($path)
            {
                echo '<img src="'.$path.'" alt="Thumbnail for '.$photo->getName().'" width="153" height="153" />';
            }

Now this works well, but, I have some images that are either square in shape, or rectangular. Giving them a size/width in the img src distorts some of them.

Is there anyway, in which I could resize/crop the images before they are displayed?

Thanks


sfThumbnailPlugin is what I've used on a number of projects and it is pretty awesome. There is an older version for Symfony 1.0 if that's what you're using. By default it uses GD, but you can have it use ImageMagick and do some pretty cool things with it.


You can probably use imagecreatefromstring and imagecopyresampled. This is code that I use, that I've changed to work with your blob. This also adds a white background if the original size width/height ratio doesn't match the destination image size.

static function CreateThumbnailFromBlob($blobData, $dstWidth = 100.0, $dstHeight = 100.0){
    $oldImg = @imagecreatefromstring($olduri);
    if($oldImg){
        $realOldW = imagesx($oldImg);
        $realOldH = imagesy($oldImg);
        $destX = 0;
        $destY = 0;

        if($realOldH>=$realOldW && $realOldH>0){
            $realY = $dstHeight;
            $realX = round($realY*$realOldW/$realOldH);
            $destX = round($dstWidth/2-$realX/2);
        }else{
            $realX = $dstWidth;
            if($realOldW>0)
                $realY = round($realX*$realOldH/$realOldW);
            else
                $realY = $dstHeight;
            $destY = round($dstHeight/2-$realY/2);
        }
        $newImg  = @imagecreatetruecolor($dstWidth, $dstHeight);
        $white   = imagecolorallocate($newImg, 255,   255,   255);
        imagefill($newImg, 1, 1, $white);
        imagecopyresampled($newImg,$oldImg,$destX,$destY,
                            0,0,$realX,$realY,$realOldW,$realOldH);
        imagedestroy($oldImg);
        return $newImg;
    }
}


How are you adding images to the database?

If it is via an upload form, the best method would be to create a thumbnail of the appropriate size/dimensions using GD or another library and store it in a second blob column.

Otherwise you can specify a single dimension in the html and the picture will retain its dimensions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜