Newscoop\Image\ImageService::calculateSize PHP Method

calculateSize() public static method

Calculates dimensions of resized image.
public static calculateSize ( $srcWidth, $srcHeight, $newWidth, $newHeight, $flags = self::FIT ) : array
return array
    public static function calculateSize($srcWidth, $srcHeight, $newWidth, $newHeight, $flags = self::FIT)
    {
        if (substr($newWidth, -1) === '%') {
            $newWidth = round($srcWidth / 100 * abs($newWidth));
            $flags |= self::ENLARGE;
            $percents = TRUE;
        } else {
            $newWidth = (int) abs($newWidth);
        }
        if (substr($newHeight, -1) === '%') {
            $newHeight = round($srcHeight / 100 * abs($newHeight));
            $flags |= empty($percents) ? self::ENLARGE : self::STRETCH;
        } else {
            $newHeight = (int) abs($newHeight);
        }
        if ($flags & self::STRETCH) {
            // non-proportional
            if (empty($newWidth) || empty($newHeight)) {
                throw new \InvalidArgumentException('For stretching must be both width and height specified.');
            }
            if (($flags & self::ENLARGE) === 0) {
                $newWidth = round($srcWidth * min(1, $newWidth / $srcWidth));
                $newHeight = round($srcHeight * min(1, $newHeight / $srcHeight));
            }
        } else {
            // proportional
            if (empty($newWidth) && empty($newHeight)) {
                throw new \InvalidArgumentException('At least width or height must be specified.');
            }
            $scale = array();
            if ($newWidth > 0) {
                // fit width
                $scale[] = $newWidth / $srcWidth;
            }
            if ($newHeight > 0) {
                // fit height
                $scale[] = $newHeight / $srcHeight;
            }
            if ($flags & self::FILL) {
                $scale = array(max($scale));
            }
            if (($flags & self::ENLARGE) === 0) {
                $scale[] = 1;
            }
            $scale = min($scale);
            $newWidth = round($srcWidth * $scale);
            $newHeight = round($srcHeight * $scale);
        }
        return array(max((int) $newWidth, 1), max((int) $newHeight, 1));
    }

Usage Example

Example #1
0
 /**
  * Get min size
  *
  * @param Newscoop\Image\ImageInterface $image
  * @return array
  */
 public function getMinSize(ImageInterface $image)
 {
     list($width, $height) = \Newscoop\Image\ImageService::calculateSize($image->getWidth(), $image->getHeight(), $this->width, $this->height, $this->getFlags());
     $ratio = max($width / (double) $image->getWidth(), $height / (double) $image->getHeight());
     return array($this->width, $this->height);
 }