我有一个快速的问题,我不太确定要进行设置。我在其他地方看到过示例,但没有什么比我的情况更具体。我想使用PHP调整图像的大小,以使图像易于阅读,而不仅仅是像使用HTML那样随意拉伸。如果它们的宽度不是250像素,也不是160像素,那么如何调整图片的大小,使其成比例但适合该空间?
谢谢!
好的,下面是我在商店中使用的Image对象。保持规模-需要GD
<?php 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; } } }
我在请求时调整图像的大小,因此页面首次加载图像时将被调整为模板所需的大小。(这意味着我不必在每次更改设计时都使共享主机崩溃,而尝试重新生成图像缩略图)
因此,在模板中,您传递了图像对象,并且当您需要图像指针时,
<img src="<?php echo $image->get_image_url(100, 100); ?>" />
您现在有了一个100x100的缩略图,该缩略图会保存到服务器中,以备日后重用