php 修改图像大小,使用PHP调整图像大小

小编典典

好的,下面是我在商店中使用的Image对象。保持规模-需要GD

class Store_Model_Image extends My_Model_Abstract

{

const PATH = STORE_MODEL_IMAGE_PATH;

const URL = "/store-assets/product-images/";

public function get_image_url($width, $height)

{

$old_file = self::PATH . $this->get_filename();

$basename = pathinfo($old_file, PATHINFO_FILENAME);

$new_name = sprintf("%s_%sx%s.jpg", $basename, $width, $height);

if(file_exists(self::PATH . $new_name))

{

return self::URL . $new_name;

}

else

{

list($width_orig, $height_orig, $image_type) = @getimagesize($old_file);

$img = FALSE;

// Get the image and create a thumbnail

switch($image_type)

{

case 1:

$img = @imagecreatefromgif($old_file);

break;

case 2:

$img = @imagecreatefromjpeg($old_file);

break;

case 3:

$img = @imagecreatefrompng($old_file);

break;

}

if(!$img)

{

throw new Zend_Exception("ERROR: Could not create image handle from path.");

}

// Build the thumbnail

if($width_orig > $height_orig)

{

$width_ratio = $width / $width_orig;

$new_width = $width;

$new_height = $height_orig * $width_ratio;

}

else

{

$height_ratio = $height / $height_orig;

$new_width = $width_orig * $height_ratio;

$new_height = $height;

}

$new_img = @imagecreatetruecolor($new_width, $new_height);

// Fill the image black

if(!@imagefilledrectangle($new_img, 0, 0, $new_width, $new_height, 0))

{

throw new Zend_Exception("ERROR: Could not fill new image");

}

if(!@imagecopyresampled($new_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig))

{

throw new Zend_Exception("ERROR: Could not resize old image onto new bg.");

}

// Use a output buffering to load the image into a variable

ob_start();

imagejpeg($new_img, NULL, 100);

$image_contents = ob_get_contents();

ob_end_clean();

// lastly (for the example) we are writing the string to a file

$fh = fopen(self::PATH . $new_name, "a+");

fwrite($fh, $image_contents);

fclose($fh);

return self::URL . $new_name;

}

}

}

我在请求时调整图像的大小,因此页面首次加载图像时将被调整为模板所需的大小。(这意味着我不必在每次更改设计时都使共享主机崩溃,而尝试重新生成图像缩略图)

因此,在模板中,您传递了图像对象,并且当您需要图像指针时,

<?php%20echo%20%24image->get_image_url(100,%20100);%20?>

您现在有了一个100x100的缩略图,该缩略图会保存到服务器中,以备日后重用

2020-05-29

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值