/** * @param ImageSize $originalSize * @param ImageSize $newSize * @return ImageSize */ private function getOptimalCrop(ImageSize $newSize) { $widthRatio = $this->getWidth() / $newSize->getWidth(); $heightRatio = $this->getHeight() / $newSize->getHeight(); if ($heightRatio < $widthRatio) { return new ImageSize($this->getWidth() / $heightRatio, $this->getHeight() / $heightRatio); } else { return new ImageSize($this->getWidth() / $widthRatio, $this->getHeight() / $widthRatio); } }
/** * @param $img * @param $type * @param ImageSize $newSize * @param ImageSize $expectedSize * @return resource */ private function crop($img, $type, ImageSize $newSize, ImageSize $expectedSize) { // Find center - this will be used for the crop $cropStartX = $newSize->getWidth() / 2 - $expectedSize->getWidth() / 2; $cropStartY = $newSize->getHeight() / 2 - $expectedSize->getHeight() / 2; // Now crop from center to exact requested size $imageCropped = imagecreatetruecolor($expectedSize->getWidth(), $expectedSize->getHeight()); switch ($type) { case IMAGETYPE_PNG: // integer representation of the color black (rgb: 0,0,0) $background = imagecolorallocate($imageCropped, 255, 0, 0); // removing the black from the placeholder imagecolortransparent($imageCropped, $background); // turning off alpha blending (to ensure alpha channel information // is preserved, rather than removed (blending with the rest of the // image in the form of black)) imagealphablending($imageCropped, false); // turning on alpha channel information saving (to ensure the full range // of transparency is preserved) imagesavealpha($imageCropped, true); break; case IMAGETYPE_GIF: // integer representation of the color black (rgb: 0,0,0) $background = imagecolorallocate($imageCropped, 255, 255, 255); // removing the black from the placeholder imagecolortransparent($imageCropped, $background); break; } imagecopyresampled($imageCropped, $img, 0, 0, $cropStartX, $cropStartY, $expectedSize->getWidth(), $expectedSize->getHeight(), $expectedSize->getWidth(), $expectedSize->getHeight()); return $imageCropped; }