Created
July 16, 2014 07:12
-
-
Save localdisk/dd207ddedc1479433bc8 to your computer and use it in GitHub Desktop.
Image Resize GD and Imagick
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace localdisk; | |
use localdisk\Bench; | |
class ImageResizer | |
{ | |
const SRC = './src.jpg'; | |
/** | |
* 縦横比をそのままに指定サイズに合わせた値を返す | |
* | |
* @param type $size 指定サイズ | |
* @param type $orgWidth 幅(オリジナル) | |
* @param type $orgHeight 高さ(オリジナル) | |
* @return array | |
*/ | |
public function getFitSize($size, $orgWidth, $orgHeight) | |
{ | |
$width = $size; | |
$height = $size; | |
$ratioOrg = $orgWidth / $orgHeight; | |
if (1 > $ratioOrg) { | |
$width = $height * $ratioOrg; | |
} else { | |
$height = $width / $ratioOrg; | |
} | |
return [$width, $height]; | |
} | |
/** | |
* GDを使用してリサイズする | |
* | |
* @param type $size 長辺 | |
* @param type $quality 品質 | |
*/ | |
public function gdResize($size, $quality = 75) | |
{ | |
(new Bench)->run(function() use ($size, $quality) | |
{ | |
// オリジナルサイズ | |
list($orgWidth, $orgHeight) = getimagesize(self::SRC); | |
// 長辺を $size に合わせた場合の、縦/横を取得 | |
list($width, $height) = $this->getFitSize($size, $orgWidth, $orgHeight); | |
// 新規イメージ | |
$newImage = imagecreatetruecolor($width, $height); | |
// リサイズ元イメージ | |
$oldImage = imagecreatefromjpeg(self::SRC); | |
imagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $width, $height, $orgWidth, $orgHeight); | |
// 出力 | |
$fileName = './gd/gd-q' . $quality . '.jpg'; | |
imagejpeg($newImage, $fileName, $quality); | |
}); | |
} | |
/** | |
* Imagickを使用してリサイズする | |
* | |
* @param type $size 長辺 | |
* @param type $quality 品質 | |
*/ | |
public function imagickResize($size, $quality = 75) | |
{ | |
(new Bench)->run(function() use ($size, $quality) | |
{ | |
// オリジナルサイズ | |
list($orgWidth, $orgHeight) = getimagesize(self::SRC); | |
// 長辺を $size に合わせた場合の、縦/横を取得 | |
list($width, $height) = $this->getFitSize($size, $orgWidth, $orgHeight); | |
// イメージ読み込み | |
$image = new \Imagick(self::SRC); | |
// リサイズ | |
$image->resizeimage($width, $height, \Imagick::FILTER_LANCZOS, 1); | |
// 圧縮 | |
$image->setimagecompression(\Imagick::COMPRESSION_JPEG); | |
$image->setimagecompressionquality($quality); | |
// ファイル名 | |
$fileName = './imagick/imagick-q' . $quality . '.jpg'; | |
// 保存 | |
$image->writeimage($fileName); | |
$image->clear(); | |
}); | |
} | |
} | |
require_once './Bench.php'; | |
(new \localdisk\ImageResizer)->gdResize(4000, 100); | |
(new \localdisk\ImageResizer)->imagickResize(4000, 100); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment