使用最大高度和宽度在php中调整图像大小

时间:2014-10-15 18:18:30

标签: php image

好的,所以我尝试使用php调整图像大小。我无法在我目前使用的服务器上安装插件。

$originalimage是我要调整大小的实际原始图片。 $width是定义$original_width的另一个参数。 $height$original_height也可以这样说。

$original_width = imagesx($originalimage);
$original_height = imagesy($originalimage);

$max_width = $thumbwidth;
$max_height = $thumbheight;

$width = $original_width;
$height = $original_height;

使用上面的预设置,我在这里开始处理这个。这有效但无法设置最大高度。例如,我将最大宽度传递为$thumbwidth,最大高度传递为$thumbheight,这将按照需要运行,直到我尝试继续使用比宽度更高的图像。 (纵向图像。)它没有完全失败,但是它无法强制执行最大高度,渲染的图像可能非常高。

if ($width > $height) {
$newwidth = $thumbwidth;
$divisor = $width / $thumbwidth;
$newheight = floor( $height / $divisor);
} else {
$newheight = $thumbheight;
$divisor = $height / $thumbheight;
$newwidth = floor( $width / $divisor );
}
$image = imagecreatetruecolor( $newwidth, $newheight );
imagecopyresampled( $image, $originalimage, 0, 0, 0, 0, $newwidth, $newheight, $original_width, $original_height );

在尝试理解这个并在几个小时后失败后,我想出了我从php.net获得的代码。正如您所看到的,有一个原因我在代码的预设置部分设置了两组彼此相等的变量。主要是因为我无法理解在第二个代码段中将$max_width称为$thumbwidth。 下面的内容也适用,直到您传入的参数大于$originalimage的宽度或高度。

# taller
if ($height > $max_height) {
    $width = ($max_height / $height) * $width;
    $height = $max_height;
}

# wider
if ($width > $max_width) {
    $height = ($max_width / $width) * $height;
    $width = $max_width;
}


$image = imagecreatetruecolor( $width, $height );
imagecopyresampled( $image, $originalimage, 0, 0, 0, 0, $width, $height, $original_width, $original_height );

对不起,我无法自己找到办法。至于这是一个重复的问题,大多数类似的问题最终都是" [在这里插入插件名称]更好地使用它。"我特意要求一个不使用其他插件或javascript的答案。 (除了我的服务器上预装的GD。) 在结束这个问题之前,我会说我正在使用imagejpeg($image);,因此完全禁止使用HTML或CSS。

3 个答案:

答案 0 :(得分:1)

这是我为我所参与的课程掀起的课程。也许它会对你有帮助吗?

<?php
class ImageHelper
{
    /**
     * @static
     * @param $source string Path for source image
     * @param $destination string Path for destination image to be placed
     * @param $targetWidth int Width of the new image (in pixels)
     * @param $targetHeight int Height of the new image (in pixels)
     * @param $strict bool
     */
    public static function createImage($source, $destination, $targetWidth, $targetHeight, $strict = false){
        $dir = dirname($destination);
        if(!is_dir($dir)){
            mkdir($dir, 0770, true);
        }
        $fileContents = file_get_contents($source);
        $image = imagecreatefromstring($fileContents);

        $thumbnail = ImageHelper::resizeImage($image, $targetWidth, $targetHeight, $strict);
        imagejpeg($thumbnail, $destination, 100);
        imagedestroy($thumbnail);
        imagedestroy($image);
    }

    /**
     * Resize an image to the specified dimensions
     * @param string $original Path to the original image
     * @param int $targetWidth Width of the new image (in pixels)
     * @param int $targetHeight Height of the new image (in pixels)
     * @param bool $strict True to crop the picture to the specified dimensions, false for best fit
     * @return bool|resource Returns the new image resource or false if the image was not resized.
     */
    public static function resizeImage($original, $targetWidth, $targetHeight, $strict = false)
    {
        $originalWidth = imagesx($original);
        $originalHeight = imagesy($original);

        $widthRatio = $targetWidth / $originalWidth;
        $heightRatio = $targetHeight / $originalHeight;

        if(($widthRatio > 1 || $heightRatio > 1) && !$strict){
            // don't scale up an image if either targets are greater than the original sizes and we aren't using a strict parameter
            $dstHeight = $originalHeight;
            $dstWidth = $originalWidth;
            $srcHeight = $originalHeight;
            $srcWidth = $originalWidth;
            $srcX = 0;
            $srcY = 0;
        }elseif ($widthRatio > $heightRatio) {
            // width is the constraining factor
            if ($strict) {
                $dstHeight = $targetHeight;
                $dstWidth = $targetWidth;
                $srcHeight = $originalHeight;
                $srcWidth = $heightRatio * $targetWidth;
                $srcX = floor(($originalWidth - $srcWidth) / 2);
                $srcY = 0;
            } else {
                $dstHeight = ($originalHeight * $targetWidth) / $originalWidth;
                $dstWidth = $targetWidth;
                $srcHeight = $originalHeight;
                $srcWidth = $originalWidth;
                $srcX = 0;
                $srcY = 0;
            }
        } else {
            // height is the constraining factor
            if ($strict) {
                $dstHeight = $targetHeight;
                $dstWidth = $targetWidth;
                $srcHeight = $widthRatio * $targetHeight;
                $srcWidth = $originalWidth;
                $srcY = floor(($originalHeight - $srcHeight) / 2);
                $srcX = 0;
            } else {
                $dstHeight = $targetHeight;
                $dstWidth = ($originalWidth * $targetHeight) / $originalHeight;
                $srcHeight = $originalHeight;
                $srcWidth = $originalWidth;
                $srcX = 0;
                $srcY = 0;
            }
        }

        $new = imagecreatetruecolor($dstWidth, $dstHeight);
        if ($new === false) {
            return false;
        }

        imagecopyresampled($new, $original, 0, 0, $srcX, $srcY, $dstWidth, $dstHeight, $srcWidth, $srcHeight);

        return $new;
    }

}

答案 1 :(得分:0)

您可以尝试此功能,如下所示。

<?php

function makeThumbnail($sourcefile,$max_width, $max_height, $endfile, $type){
// Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it
// and places it at endfile (path/to/thumb.jpg).

// Load image and get image size.

//   
switch($type){
    case'image/png':
        $img = imagecreatefrompng($sourcefile);
        break;
        case'image/jpeg':
        $img = imagecreatefromjpeg($sourcefile);
        break;
        case'image/gif':
        $img = imagecreatefromgif($sourcefile);
        break;
        default : 
        return 'Un supported format';
}

$width = imagesx( $img );
$height = imagesy( $img );

if ($width > $height) {
    if($width < $max_width)
        $newwidth = $width;

    else

    $newwidth = $max_width; 


    $divisor = $width / $newwidth;
    $newheight = floor( $height / $divisor);
}
else {

     if($height < $max_height)
         $newheight = $height;
     else
         $newheight =  $max_height;

    $divisor = $height / $newheight;
    $newwidth = floor( $width / $divisor );
}

// Create a new temporary image.
$tmpimg = imagecreatetruecolor( $newwidth, $newheight );

    imagealphablending($tmpimg, false);
    imagesavealpha($tmpimg, true);

// Copy and resize old image into new image.
imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Save thumbnail into a file.

//compressing the file


switch($type){
    case'image/png':
        imagepng($tmpimg, $endfile, 0);
        break;
    case'image/jpeg':
        imagejpeg($tmpimg, $endfile, 100);
        break;
    case'image/gif':
        imagegif($tmpimg, $endfile, 0);
        break;  

}

// release the memory
   imagedestroy($tmpimg);
   imagedestroy($img);
}
?>

该功能有五个参数。

>   $sourcefile - Specicifies the temporary location of your image file
>     $max_width - Specifies the possible maximum width  
>     $max_height - Specifies the possible maximum width   
>     $endfile  - Specifies the directory to save the image 
>     $type - Specifies the image file type

下载演示代码here

答案 2 :(得分:0)

我在构建图库页面的缩略图时遇到了非常相似的问题。我在上面尝试了Daniel Nyamasyo解决方案,但无法通过“ $ img = imagecreatefromjpeg($ sourcefile);”行,而不会收到“警告:imagecreatefromjpeg无法打开流:HTTP请求失败!HTTP / 1.1 400错误请求”,无论我用什么$ sourcefile喂它。 我想出了这种肮脏的方法。

    <?php
    // Some variables
    $thumb_width = 162; // The maximum values you want
    $thumb_height = 122;
    $thumb_pointer = 'thumbs';  // Put your output folder here which must exist

    $img = imagecreatefromjpeg( $image_name);
    $width = imagesx( $img );
    $height = imagesy( $img );
    if ($width>=$height)
    {
        // Now calculate thumbnail size
        $new_width = $thumb_width;
        $new_height = floor( $height * ($thumb_width / $width));
        // The 'dirty' bit I found was needed for square or near square images      
        while ($new_height > $thumb_height)
        {
            $new_width = floor($new_width * 0.99);
            $new_height = floor($new_height * 0.99);
        }
    }
    else
    {
        $new_height = $thumb_height;
        $new_width =  floor($width * ($thumb_height / $height));
    }
    // Create a new temporary image 
    $tmp_img = imagecreatetruecolor( $new_width, $new_height );
    // Copy and resize old image into new image 
    imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
    // Save the thumbnail into a file   
    imagejpeg( $tmp_img, $thumb_pointer.'/'.$image_name);
?>