栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用PHP调整图像大小

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用PHP调整图像大小

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

<?phpclass 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;        }    }}

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

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

<img src="<?php echo $image->get_image_url(100, 100); ?>" />

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/421709.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号