/**
 * @param $img 图片地址
 * @param string $width 宽
 * @param string $height 高
 * @param string $ratio 保持原比例
 * @return string 生成的地址
 */
public function resize_fuc($img, $width, $height, $ratio)
{

	$info = get_img_info($img);
	$name = pathinfo($img)['filename'];
	$dirname = pathinfo($img)['dirname'];
	$ext = pathinfo($img)['extension'];

	$im = NULL;
	$type = strtolower($info['type']);

	if (!in_array($type, ['jpg', 'jpeg', 'gif', 'png'])) {
		return FALSE;
	}
	$type = ($type == 'jpg' ? 'jpeg' : $type);

	$scale = $info['width'] / $info['height'];

	if ($ratio == TRUE) {
		$forScale = $width / $height;
		$x = 0;
		$y = 0;
		if ($scale >= $forScale) {
			$width = (int)($height * $scale);
			$rate = $info['height']/$height;
		} else {
			$height = (int)($width / $scale);
			$rate = $info['width']/$width;
		}
	} else {
		$forScale = $width / $height;
		if ($scale >= $forScale) {
			$x = ($info['width'] - $info['height'] * $forScale) / 2;
			$y = 0;
			$rate = $info['height'] / $height;
		} else {
			$x = 0;
			$y = ($info['height'] - $info['width'] / $forScale) / 2;
			$rate = $info['width'] / $width;
		}
	}

	if($width>$info['width'] || $height>$info['height']){
		return;
	}


	$imageCreateFun = 'imagecreatefrom' . $type;
	$im = $imageCreateFun($img);
	$thumb = $dirname . '/' . $name . '_tmp' . "." . $ext;

	$imageFun = 'image' . $type;
	$imageFun($im, $thumb);

	$thumbNew = imagecreatetruecolor($width, $height);

	imagecopyresampled(
		$thumbNew, $im,
		0, 0, intval($x), intval($y),
		intval($width * 1), intval($height * 1), intval($width * $rate), intval($height * $rate)
	);

	$imageFun($thumbNew, $thumb);

	imagedestroy($im);
	imagedestroy($thumbNew);

	rename($thumb,$img);
	return $img;
}
function get_img_info($img) {
    if(!is_file($img) || !in_array(strtolower(pathinfo($img)['extension']),['jpg','jpeg','bmp','gif','png'])){
        return false;
    }
    $img_info = getimagesize($img);
    if ($img_info !== false) {
        $img_type = strtolower(substr(image_type_to_extension($img_info[2]), 1));
        $info = array("width" => $img_info[0], "height" => $img_info[1], "type" => $img_type, "mime" => $img_info['mime'], );
        return $info;
    } else {
        return false;
    }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注