ここでは画像比率を保ちPHPで画像のリサイズを行います。
1.画像ファイル名はランダム
2.メイン画像 (横:700 高さ:比率を保ちリサイズ)
3.サムネイル作成(縦長:横216 横長:高さ163)
4.smart_resize_image.phpライブラリを使用
サンプルソース
require_once("smart_resize_image.php");
/**
* 画像アップロード
* @param $tmp
* @param $mainPath
* @param $thumPath
* @return boolean|$fileName
*/
public function upImage($tmp, $mainPath, $thumPath){
$fileName = md5(uniqid(rand(), true));
$fileName .= '.'.substr(strrchr($tmp['name'], '.'), 1);
$mainPath .= $fileName;
$thumPath .= $fileName;
if (!move_uploaded_file($tmp['tmp_name'], $mainPath)) {
return false;
}
$arrSize = getimagesize($mainPath);
$width = $arrSize[0];
$height = $arrSize[1];
if ($width != 700) {
$num = 700 * $height / $width;
$rheight = floor($num);
smart_resize_image($mainPath, 700, $rheight, false, 'file', true);
}
copy($mainPath, $thumPath);
// サムネイル
$arrSize = getimagesize($thumPath);
$width = $arrSize[0];
$height = $arrSize[1];
if ($width < $height) {
$num = 216 * $height / $width;
$rheight = floor($num);
smart_resize_image($thumPath, 216, $rheight, false, 'file', true);
}
else {
$num = 163 * $width / $height;
$rwidth = floor($num);
smart_resize_image($thumPath, $rwidth, 163, false, 'file', true);
}
return $fileName;
}
解説
ランダムのファイル名
$fileName = md5(uniqid(rand(), true));
画像の拡張子を取得
$fileName .= ‘.’.substr(strrchr($tmpName, ‘.’), 1);
加工する画像のサイズを取得
$arrSize = getimagesize($mainPath);
横 $arrSize[0];
高さ $arrSize[1];
