PHP GD のスニペット集
このページは、PHP の GD (画像処理) のスニペットなどをまとめる予定のページです。
目次
注意
- コードのライセンスは CC0 (クレジット表示不要、改変可、商用可) です。
- 一部 GD ではない (画像関連の) スニペットもあります。
- スニペット中の
$img
は画像リソース、$color
は色リソースです。
スニペット
画像リソースの生成
$width = 100;
$height = 100;
$img = imagecreatetruecolor($width, $height);
画像の読み込み
$path = 'test.png';
$img = imagecreatefrompng($path);
$path = 'test.jpg';
$img = imagecreatefrompng($path);
$path = 'test.png';
list($width, $height, $type, $attr) = getimagesize($path);
switch ($type) {
case IMAGETYPE_GIF:
$img = imagecreatefromgif($path);
break;
case IMAGETYPE_JPEG:
$img = imagecreatefromjpeg($path);
break;
case IMAGETYPE_PNG:
$img = imagecreatefrompng($path);
break;
default:
return;
}
色リソースの生成
$color = imagecolorallocate($img, 0xff, 0xff, 0xff);
$color = imagecolorallocate($img, 0x00, 0x00, 0x00);
$color = imagecolorallocate($img, 0xff, 0x00, 0x00);
塗りつぶし
imagefill($img, 0, 0, $color);
画像リソースの保存
$savePath = 'test.png';
imagepng($img, $savePath);
imagedestroy($img);
$savePath = 'test.jpg';
imagejpeg($img, $savePath, 95);
imagedestroy($img);
Data URL に変換
$path = 'test.png';
list($width, $height, $type, $attr) = getimagesize($path);
$mime = image_type_to_mime_type($type);
$imageData = file_get_contents($path);
$dataUrl = 'data:' . $mime . ';base64,' . base64_encode($imageData);
リサイズ (PNG)
$srcPath = 'test.png';
$destPath = 'resize.png';
$resize = 100; // 幅の最大長 (横幅が長い場合は横幅、縦幅が長い場合は縦幅の長さ)
list($srcWidth, $srcHeight, $type, $attr) = getimagesize($srcPath);
if ($srcWidth >= $srcHeight) {
$newWidth = $resize;
$newHeight = $newWidth * ($srcHeight / $srcWidth);
}
else {
$newHeight = $resize;
$newWidth = $newHeight * ($srcWidth / $srcHeight);
}
$src = imagecreatefrompng($srcPath);
$dest = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($dest, $src, 0, 0, 0, 0, $newWidth, $newHeight, $srcWidth, $srcHeight);
imagepng($dest, $destPath);
imagedestroy($img);