在 php 中调整图像大小仅供查看

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9581592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:10:42  来源:igfitidea点击:

Resizing the image in php for viewing purposes only

phpimageresizecrop

提问by Mike Sanchez

Okay, the reason I posted this is because I wasn't sure what to search for. I'll try to explain it as clearly as I can.

好吧,我发布这个的原因是因为我不确定要搜索什么。我会尽量解释清楚。

Say, I have an image sized 800x600. The box I've allotted for the image is 150x150 and has to be satisfied at all times. I can only allow an image to be shown at a maximum size of 150px for both height and width. So, technically, the image has to be scaled down to 200x150.

说,我有一个大小为 800x600 的图像。我为图像分配的框是 150x150,必须始终满足。我只能允许以最大 150 像素的高度和宽度显示图像。因此,从技术上讲,图像必须缩小到 200x150。

Now, the question:

现在,问题

Is there a way I can crop the height so it only shows 150x150? This is for viewing purposes only. I don't need to save the image as a new file.

有没有办法可以裁剪高度,使其只显示 150x150?这仅用于查看目的。我不需要将图像保存为新文件。

A good example is your profile page in Twitter. It shows your profile image cropped but when you click on it, you still get the image you originally uploaded.

一个很好的例子是你在 Twitter 上的个人资料页面。它显示您的个人资料图片被裁剪,但当您点击它时,您仍然会看到您最初上传的图片。

[EDIT]Here's what I'm trying to achieve. Get the smaller side in terms of pixels, resize it to 150px then hide the overflowing part of the other side. Again, no saving involved. Just for people's viewing pleasure.

[编辑]这就是我想要实现的目标。以像素为单位获取较小的一侧,将其调整为 150 像素,然后隐藏另一侧的溢出部分。同样,不涉及储蓄。只是为了人们的观赏乐趣。

What I'm trying to accomplish

我想要完成的事情

回答by Valeh Hajiyev

I use a simple PHP class which has several options for resizing. You can easily store the thumbnails via this class. As @jeroen said, you only have to do it once and they can be cached. It just requires PHP5 and GD library. Here is usage example:

我使用一个简单的 PHP 类,它有几个调整大小的选项。您可以通过此类轻松存储缩略图。正如@jeroen 所说,你只需要做一次,它们就可以被缓存。它只需要 PHP5 和 GD 库。这是使用示例:

// *** Include the class
include("resize-class.php");

// *** 1) Initialise / load image
$resizeObj = new resize('sample.jpg');

// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
$resizeObj -> resizeImage(150, 150, 'crop');

// *** 3) Save image ('image-name', 'quality [int]')
$resizeObj -> saveImage('sample-resized.jpg', 100);

And this is that class:

这是那个班级:

<?php
        Class resize
        {
            // *** Class variables
            private $image;
            private $width;
            private $height;
            private $imageResized;

            function __construct($fileName)
            {
                // *** Open up the file
                $this->image = $this->openImage($fileName);

                // *** Get width and height
                $this->width  = imagesx($this->image);
                $this->height = imagesy($this->image);
            }

            ## --------------------------------------------------------

            private function openImage($file)
            {
                // *** Get extension
                $extension = strtolower(strrchr($file, '.'));

                switch($extension)
                {
                    case '.jpg':
                    case '.jpeg':
                        $img = @imagecreatefromjpeg($file);
                        break;
                    case '.gif':
                        $img = @imagecreatefromgif($file);
                        break;
                    case '.png':
                        $img = @imagecreatefrompng($file);
                        break;
                    default:
                        $img = false;
                        break;
                }
                return $img;
            }

            ## --------------------------------------------------------

            public function resizeImage($newWidth, $newHeight, $option="auto")
            {
                // *** Get optimal width and height - based on $option
                $optionArray = $this->getDimensions($newWidth, $newHeight, $option);

                $optimalWidth  = $optionArray['optimalWidth'];
                $optimalHeight = $optionArray['optimalHeight'];


                // *** Resample - create image canvas of x, y size
                $this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
                imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);


                // *** if option is 'crop', then crop too
                if ($option == 'crop') {
                    $this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
                }
            }

            ## --------------------------------------------------------

            private function getDimensions($newWidth, $newHeight, $option)
            {

               switch ($option)
                {
                    case 'exact':
                        $optimalWidth = $newWidth;
                        $optimalHeight= $newHeight;
                        break;
                    case 'portrait':
                        $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                        $optimalHeight= $newHeight;
                        break;
                    case 'landscape':
                        $optimalWidth = $newWidth;
                        $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                        break;
                    case 'auto':
                        $optionArray = $this->getSizeByAuto($newWidth, $newHeight);
                        $optimalWidth = $optionArray['optimalWidth'];
                        $optimalHeight = $optionArray['optimalHeight'];
                        break;
                    case 'crop':
                        $optionArray = $this->getOptimalCrop($newWidth, $newHeight);
                        $optimalWidth = $optionArray['optimalWidth'];
                        $optimalHeight = $optionArray['optimalHeight'];
                        break;
                }
                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }

            ## --------------------------------------------------------

            private function getSizeByFixedHeight($newHeight)
            {
                $ratio = $this->width / $this->height;
                $newWidth = $newHeight * $ratio;
                return $newWidth;
            }

            private function getSizeByFixedWidth($newWidth)
            {
                $ratio = $this->height / $this->width;
                $newHeight = $newWidth * $ratio;
                return $newHeight;
            }

            private function getSizeByAuto($newWidth, $newHeight)
            {
                if ($this->height < $this->width)
                // *** Image to be resized is wider (landscape)
                {
                    $optimalWidth = $newWidth;
                    $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                }
                elseif ($this->height > $this->width)
                // *** Image to be resized is taller (portrait)
                {
                    $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                    $optimalHeight= $newHeight;
                }
                else
                // *** Image to be resizerd is a square
                {
                    if ($newHeight < $newWidth) {
                        $optimalWidth = $newWidth;
                        $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                    } else if ($newHeight > $newWidth) {
                        $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                        $optimalHeight= $newHeight;
                    } else {
                        // *** Sqaure being resized to a square
                        $optimalWidth = $newWidth;
                        $optimalHeight= $newHeight;
                    }
                }

                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }

            ## --------------------------------------------------------

            private function getOptimalCrop($newWidth, $newHeight)
            {

                $heightRatio = $this->height / $newHeight;
                $widthRatio  = $this->width /  $newWidth;

                if ($heightRatio < $widthRatio) {
                    $optimalRatio = $heightRatio;
                } else {
                    $optimalRatio = $widthRatio;
                }

                $optimalHeight = $this->height / $optimalRatio;
                $optimalWidth  = $this->width  / $optimalRatio;

                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }

            ## --------------------------------------------------------

            private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
            {
                // *** Find center - this will be used for the crop
                $cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
                $cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );

                $crop = $this->imageResized;
                //imagedestroy($this->imageResized);

                // *** Now crop from center to exact requested size
                $this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
                imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
            }

            ## --------------------------------------------------------

            public function saveImage($savePath, $imageQuality="100")
            {
                // *** Get extension
                $extension = strrchr($savePath, '.');
                $extension = strtolower($extension);

                switch($extension)
                {
                    case '.jpg':
                    case '.jpeg':
                        if (imagetypes() & IMG_JPG) {
                            imagejpeg($this->imageResized, $savePath, $imageQuality);
                        }
                        break;

                    case '.gif':
                        if (imagetypes() & IMG_GIF) {
                            imagegif($this->imageResized, $savePath);
                        }
                        break;

                    case '.png':
                        // *** Scale quality from 0-100 to 0-9
                        $scaleQuality = round(($imageQuality/100) * 9);

                        // *** Invert quality setting as 0 is best, not 9
                        $invertScaleQuality = 9 - $scaleQuality;

                        if (imagetypes() & IMG_PNG) {
                             imagepng($this->imageResized, $savePath, $invertScaleQuality);
                        }
                        break;

                    // ... etc

                    default:
                        // *** No extension - No save.
                        break;
                }

                imagedestroy($this->imageResized);
            }


            ## --------------------------------------------------------

        }
?>

回答by hakre

You load the image, resize it first so that it has the minimum side being 150, then you crop to the 150 width/height relative to the center. Then you just output your image:

您加载图像,首先调整其大小,使其最小边为 150,然后相对于中心裁剪为 150 的宽度/高度。然后你只需输出你的图像:

WideImage::load('yourfile.png/jpg/...')
    ->resize(150, 150, 'outside', 'any')
    ->crop('center', 'center', 150, 150)
    ->output('png');

You find the sourcecode, documentation, online demos and the API documentation here: WideImage.

您可以在此处找到源代码、文档、在线演示和 API 文档:WideImage

Let me know if you've still got questions.

如果您还有问题,请告诉我。

回答by user1524615

It is very easy to use here is the class http://timthumb.googlecode.com/svn/trunk/timthumb.phphere are the params http://viralpatel.net/blogs/resize-image-dynamically-php/I have tested looks works great

这是非常容易使用这里是类http://timthumb.googlecode.com/svn/trunk/timthumb.php这里是参数http://viralpatel.net/blogs/resize-image-dynamically-php/我经测试看起来效果很好

example is < img src="/script/timthumb.php?src=/some/path/myimage.png&w=100&h=80" alt="resized image" />

例子是 < img src="/script/timthumb.php?src=/some/path/myimage.png&w=100&h=80" alt="resized image" />

回答by LJ Wilson

Why not just do this with CSS and not have to use the server for any processing? There are a couple of ways to accomplish this using CSS. The Clip method is one I have used before, and a google search will bring you several results. Hereis one site that covers this well

为什么不直接用 CSS 来做这件事,而不必使用服务器进行任何处理?有几种方法可以使用 CSS 来实现这一点。Clip 方法是我以前使用过的一种方法,谷歌搜索会给你带来几个结果。 是一个网站,涵盖了这一点

回答by jeroen

I would store the thumbnails so that you only have to do it once and they can be cached. If your aspect ratio is fixed, I would scale them down to fit in a 200x200 box (there are some php answers here about that so I'll skip it). If the aspect ratio varies, I would use a safe value so that it always covers your 150x150 box (like 300x300).

我会存储缩略图,这样你只需要做一次,它们就可以被缓存。如果您的纵横比是固定的,我会将它们缩小以适合 200x200 的框(这里有一些 php 答案,所以我会跳过它)。如果纵横比变化,我会使用一个安全值,以便它始终覆盖您的 150x150 框(如 300x300)。

Then I would set the thumbnail image as a background image for the image box in css and you get exactly the effect you want:

然后我将缩略图设置为 css 中图像框的背景图像,您将获得所需的效果:

.img_box {
  background-repeat: no-repeat;
  background-position: center center;
  background-image: url(/path/to/image);
}

To enhance the experience for css3 capable browsers you can set:

要增强支持 css3 的浏览器的体验,您可以设置:

background-size: cover;

to the box so that it fits exactly (maintaining aspect ratio).

到盒子,使其完全适合(保持纵横比)。

回答by Nishchal Gautam

I don't know this fully but once I created a program which would view us thumbnail images for our images. And the code goes like this:

我不完全知道这一点,但是一旦我创建了一个程序,该程序可以查看我们图像的缩略图。代码是这样的:

$src=imagecreatefromjpg("file.jpg");
$dest=imagecreatetruecolor($destwidth,$destheight);
$src1=imagecopyresized($dest,$src,0,0,0,0,$destwidth,$destheight,$widthresource,$heightresource);
echo imagejpeg($dest);

changing the parameters of imagecopyresized which are set to 0,0,0,0 here will crop your image from x1,y1 to x2,y2 Hope this helps

在这里更改设置为 0,0,0,0 的 imagecopyresized 参数会将您的图像从 x1,y1 裁剪为 x2,y2 希望这会有所帮助

回答by Juice

<?php
    $output_width =80;
    $output_height=80;

    if(isset($_GET['height'])){
       $output_height=$_GET['height'];
    }
     if(isset($_GET['width'])){
       $output_width=$_GET['width'];
    }

   $path = ( (isset($_REQUEST['path']))? $_REQUEST['path'] : "");
   //echo  $path;exit;
    $size_arr = getimagesize($path);
    if ($size_arr[2]==IMAGETYPE_GIF)
        $image = imagecreatefromgif($path);
    else if ($size_arr[2]==IMAGETYPE_JPEG)
        $image = imagecreatefromjpeg($path);
    else if ($size_arr[2]==IMAGETYPE_PNG)
        $image = imagecreatefrompng($path);
    else
        die_default_image();

    $tmpname = tempnam( sys_get_temp_dir() , "phptmp");

    resize_image($tmpname, $image, $size_arr, $output_width, $output_height);

    header('Content-Type: image/jpg');
    header('Content-Disposition: inline; filename="'.basename($path).'"');
    echo file_get_contents( $tmpname );
    unlink( $tmpname );
    die('');


function die_default_image()
{
    //43byte 1x1 transparent pixel gif
    header("content-type: image/gif");
    echo base64_decode("R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==");
}

function resize_image($thumbname, $image, $size_arr, $max_width, $max_height)//maintain aspect ratio
{
    $width  = $max_width;
    $height = $max_height;
    list($width_orig, $height_orig, $img_type) = $size_arr;
    $ratio_orig = $width_orig/$height_orig;

    if ($width/$height > $ratio_orig) {
       $width = floor($height*$ratio_orig);
    } else {
       $height = floor($width/$ratio_orig);
    }

    // Resample
    $tempimg = imagecreatetruecolor($width, $height);
    imagecopyresampled($tempimg, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
    imagejpeg($tempimg, $thumbname, 80);
}

if (!function_exists('sys_get_temp_dir')) {
  function sys_get_temp_dir() {
    if (!empty($_ENV['TMP'])) { return realpath($_ENV['TMP']); }
    if (!empty($_ENV['TMPDIR'])) { return realpath( $_ENV['TMPDIR']); }
    if (!empty($_ENV['TEMP'])) { return realpath( $_ENV['TEMP']); }
    $tempfile=tempnam(uniqid(rand(),TRUE),'');
    if (file_exists($tempfile)) {
    unlink($tempfile);
    return realpath(dirname($tempfile));
    }
  }
}
?>

Save the file as imageresize.php and put this file in your image folder and just use the code like this to show image

将文件另存为 imageresize.php 并将此文件放在您的图像文件夹中,只需使用这样的代码来显示图像

<img src="<?=base_url().'uploads/imageresize.php?path='.$image."&width=150 &height=150";?>" />

you can use this code to show images in different sizes.

您可以使用此代码显示不同大小的图像。

回答by riyuk

Here's my Image Resize Class. The Class can get the Result that you want (cropping/centered cropping/etc.)... and a lot more ;-)

这是我的图像调整大小类。班级可以获得您想要的结果(裁剪/居中裁剪/等)......以及更多;-)

I dont explain everything but if you got any questions just ask me.

我不解释一切,但如果你有任何问题,尽管问我。

<?php
final class Img {
    /**
     * Usage:
     * Img::resizeImage( 'sample.png', null, array( 'x' => 150, 'y' => 150 ) )
     * Outputs a Image
     * 
     * Img::resizeImage( 'sample.png', 'crop.jpg', array( 'x' => 200, 'y' => 200 ) )
     * Saves a Image
     *
     * @static
     * @param string $source
     * @param null|string $destination
     * @param array $options
     * @return void
     * @throws Exception
     */
    public static function resizeImage( $source, $destination = null, $options = array() ) {
        if( !file_exists( $source ) || ( is_string( $destination ) && !is_writable( dirname( $destination ) ) ) ) {
            throw new Exception( 'Quelldatei existiert nicht oder Zielverzeichnis ist nicht beschreibbar.' );
        }

        #@ini_set ('memory_limit', '64M' );

        $defaultOptions = array(
            'x' => 100,
            'y' => 100,
            'maxX' => 1000,
            'maxY' => 1000,
            'zoom_crop' => 1,
            'quality' => 90,
            'align' => 'c', // [c]enter, [b]ottom, [t]op, [l]eft, [r]ight
            'filters' => '',
            'sharpen' => 0,
            'canvas' => 'ffffff',
        );
        $options = array_merge( $defaultOptions, $options );

        $sData = getimagesize( $source );
        $origType = $sData[2];
        $mimeType = $sData['mime'];

        if( !preg_match( '/^image\/(?:gif|jpg|jpeg|png)$/i', $mimeType ) ) {
            throw new Exception( 'The image being resized is not a valid gif, jpg or png.' );
        }

        if( !function_exists( 'imagecreatetruecolor' ) ) {
            throw new Exception( 'GD Library Error: imagecreatetruecolor does not exist' );
        }

        if( function_exists( 'imagefilter' ) && defined( 'IMG_FILTER_NEGATE' ) ) {
            $imageFilters = array (
                    1 => array (IMG_FILTER_NEGATE, 0),
                    2 => array (IMG_FILTER_GRAYSCALE, 0),
                    3 => array (IMG_FILTER_BRIGHTNESS, 1),
                    4 => array (IMG_FILTER_CONTRAST, 1),
                    5 => array (IMG_FILTER_COLORIZE, 4),
                    6 => array (IMG_FILTER_EDGEDETECT, 0),
                    7 => array (IMG_FILTER_EMBOSS, 0),
                    8 => array (IMG_FILTER_GAUSSIAN_BLUR, 0),
                    9 => array (IMG_FILTER_SELECTIVE_BLUR, 0),
                    10 => array (IMG_FILTER_MEAN_REMOVAL, 0),
                    11 => array (IMG_FILTER_SMOOTH, 0),
            );
        }

        $destX = min( $options['x'], $options['maxX'] );
        $destY = min( $options['y'], $options['maxY'] );

        switch( $mimeType ) {
            case 'image/jpg':
            case 'image/jpeg':
            case 'image/pjgpg':
                $image = imagecreatefromjpeg( $source );
                break;
            case 'image/png':
                $image = imagecreatefrompng( $source );
                break;
            case 'image/gif':
                $image = imagecreatefromgif( $source );
                break;
        }

        if( !isset( $image ) ) {
            throw new Exception( 'Could not open Image' );
        }

        $width = imagesx( $image );
        $height = imagesy( $image );
        $originX = $originY = 0;

        if( $destX > 0 && $destY == 0 ) {
            $destY = floor( $height * ( $destX / $width ) );
        } else if( $destY > 0 && $destX == 0 ) {
            $destX = floor( $width * ( $destY / $height ) );
        }

        // scale down and add borders
        if( $options['zoom_crop'] == 3 ) {
            $finalY = $height * ( $destX / $width );

            if( $finalY > $destY ) {
                $destX = $width * ( $destY / $height );
            } else {
                $destY = $finalY;
            }
        }

        $canvas = imagecreatetruecolor( $destX, $destY );
        imagealphablending( $canvas, false );

        if( strlen( $options['canvas'] ) < 6 ) {
            $options['canvas'] = 'ffffff';
        }

        $canvasColorR = hexdec( substr( $options['canvas'], 0, 2 ) );
        $canvasColorG = hexdec( substr( $options['canvas'], 2, 2 ) );
        $canvasColorB = hexdec( substr( $options['canvas'], 2, 2 ) );

        // transparentes bild erstellen
        $color = imagecolorallocatealpha( $canvas, $canvasColorR, $canvasColorG, $canvasColorB, 127 );
        imagefill( $canvas, 0, 0, $color );

        // scale down and add borders
        if( $options['zoom_crop'] == 2 ) {
            $finalY = $height * ( $destX / $width );

            if( $finalY > $destY ) {
                $originX = $destX / 2;
                $destX = $width * ( $destY / $height );
                $originX = round( $originX - ( $destX / 2 ) );
            } else {
                $originY = $destY / 2;
                $destY = $finalY;
                $originY = round( $originY - ( $destY / 2 ) );
            }
        }

        // restore transparency blending
        imagesavealpha( $canvas, true );

        if( $options['zoom_crop'] > 0 ) {

            $srcX = $srcY = 0;
            $srcW = $width;
            $srcH = $height;

            $cmpX = $width / $destX;
            $cmpY = $height / $destY;

            // calculate x or y coordinate and width or height of source
            if( $cmpX > $cmpY ) {
                // breitformat
                $srcW = round( $width / $cmpX * $cmpY );
                $srcX = round( ( $width - ( $width / $cmpX * $cmpY ) ) / 2 );
            } elseif( $cmpY > $cmpX ) {
                $srcH = round( $height / $cmpY * $cmpX );
                $srcY = round( ( $height - ( $height / $cmpY * $cmpX ) ) / 2 );
            }

            // pos cropping
            if( strlen( $options['align'] ) ) {
                if( strpos( $options['align'], 't') !== false) {
                    $srcY = 0;
                }
                if( strpos( $options['align'], 'b') !== false) {
                    $srcY = $height - $srcH;
                }
                if( strpos( $options['align'], 'l') !== false) {
                    $srcX = 0;
                }
                if( strpos( $options['align'], 'r') !== false) {
                    $srcX = $width - $srcW;
                }
            }

            imagecopyresampled( $canvas, $image, $originX, $originY, $srcX, $srcY, $destX, $destY, $srcW, $srcH );

        } else {
            imagecopyresampled( $canvas, $image, 0, 0, 0, 0, $destX, $destY, $width, $height );
        }

        // @todo filterm?glichkeit über optionen ausbessern
        if( strlen( $options['filters'] ) && function_exists( 'imagefilter' ) && defined( 'IMG_FILTER_NEGATE' ) ) {
            // apply filters to image
            $filterList = explode( '|', $options['filters'] );
            foreach( $filterList as $fl ) {
                $filterSettings = explode (',', $fl);
                if (isset ($imageFilters[$filterSettings[0]])) {

                    for ($i = 0; $i < 4; $i ++) {
                        if (!isset ($filterSettings[$i])) {
                            $filterSettings[$i] = null;
                        } else {
                            $filterSettings[$i] = (int) $filterSettings[$i];
                        }
                    }
                    switch ($imageFilters[$filterSettings[0]][1]) {
                        case 1:
                            imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1]);
                            break;
                        case 2:
                            imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2]);
                            break;
                        case 3:
                            imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3]);
                            break;
                        case 4:
                            imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3], $filterSettings[4]);
                            break;
                        default:
                            imagefilter ($canvas, $imageFilters[$filterSettings[0]][0]);
                            break;
                    }
                }
            }
        }

        if( $options['sharpen'] > 0 && function_exists( 'imageconvolution' ) ) {
            $sharpenMatrix = array (
                            array (-1,-1,-1),
                            array (-1,16,-1),
                            array (-1,-1,-1),
                            );

            $divisor = 8;
            $offset = 0;

            imageconvolution( $canvas, $sharpenMatrix, $divisor, $offset );
        }

        //Straight from Wordpress core code. Reduces filesize by up to 70% for PNG's
        if( ( IMAGETYPE_PNG == $origType || IMAGETYPE_GIF == $origType ) &&
            function_exists( 'imageistruecolor' ) && !imageistruecolor( $image ) &&
            imagecolortransparent( $image ) > 0 ) {
            imagetruecolortopalette( $canvas, false, imagecolorstotal( $image ) );
        }

        if( null === $destination ) {
            header( "Cache-Control: no-store, no-cache, must-revalidate" );
            header( "Cache-Control: post-check=0, pre-check=0", false);
            header( "Pragma: no-cache" );
            header( "Expires: Sat, 26 Jul 1997 05:00:00 GMT" );
            header( "Last-Modified: " . date( "D, d M Y H:i:s" ) . " GMT" );

        }

        switch( $mimeType ) {
            case 'image/jpg':
            case 'image/jpeg':
            case 'image/pjgpg':
                if( null === $destination ) {
                    header("Content-type: image/jpeg");
                }
                @imagejpeg( $canvas, $destination, $options['quality'] );
                break;
            case 'image/png':
                if( null === $destination ) {
                    header("Content-type: image/png");
                }
                @imagepng( $canvas, $destination, floor( $options['quality'] * 0.09 ) );
                break;
            case 'image/gif':
                if( null === $destination ) {
                    header("Content-type: image/gif");
                }
                @imagegif( $canvas, $destination );
                break;
            default:
                throw new Exception( 'Fehler beim schreiben' );
                break;
        }

        imagedestroy( $canvas );
        imagedestroy( $image );
    }
}

回答by Erwin Brandstetter

I have a shell scriptin place that does exactly what you need with ImageMagick:

我有一个shell 脚本,它可以完全满足您对ImageMagick 的需求

#!/bin/sh
SOURCE='/path/to/img'
FILE='myfile.jpg'

convert $SOURCE/$FILE -thumbnail 150x150^\> -quality 85% \
        -gravity center -extent 150x150 ${SOURCE}150/$FILE
  • This resizes to a box covering 150x150 - the ^after 150x150is essential!
  • The -thumbnailoption strips all meta-information except for color profiles and is very fast.
  • Then it cuts a box with 150x150 from the center (-gravity center -extent 150x150) - exactly what you want.
  • In addition I set -quality 85%which should be plenty while reducing file size a lot.
  • In this example I take the image from an imgdirectory and write the thumbnail with the same filename to a img150directory right next to it.
  • 这将调整为一个覆盖 150x150 的盒子 -^之后150x150是必不可少的!
  • -thumbnail选项会去除除颜色配置文件之外的所有元信息,并且速度非常快。
  • 然后它从中心 ( -gravity center -extent 150x150)切出一个 150x150 的盒子- 正是您想要的。
  • 此外,我设置了-quality 85%哪些应该足够多,同时大量减少文件大小。
  • 在此示例中,我从img目录中获取图像并将具有相同文件名的缩略图写入其img150旁边的目录。

Experiment for best results.

试验以获得最佳结果。

I had help from:
http://www.imagemagick.org/Usage/files/
http://www.imagemagick.org/Usage/resize/
http://www.imagemagick.org/script/command-line-options.php#thumbnail

我得到了帮助:
http://www.imagemagick.org/Usage/files/
http://www.imagemagick.org/Usage/resize/
http://www.imagemagick.org/script/command-line-options .php#缩略图

回答by DACrosby

As a few have mentioned, this can be done with CSS if you're not saving the image. Although load times will be hurt (downloading a 800x600 image vs downloading a 150x150 image).

正如一些人提到的,如果您不保存图像,可以使用 CSS 来完成。虽然加载时间会受到影响(下载 800x600 图像与下载 150x150 图像)。

HTML:

HTML:

<div class="imgHold">
     <img src="imgSrc.jpg" />
</div>

CSS:

CSS:

div{
     overflow:hidden;
}
img{
    width:150px;
    height:200px;
    margin-top:-25px;
}