динамически масштабировать изображения в php jpg / png / gif

Есть ли простой способ динамического масштабирования изображения в php?

Я хотел бы специально использовать какую-то функцию, где я могу вставить ее в свой хемл, например

<img src=image.php?img=boss.jpg&width=500>

и, конечно, затем он масштабирует изображение до любой высоты, ограничивающей его шириной 500 пикселей.

я ценю любой вклад, спасибо.

РЕДАКТИРОВАТЬ обязательно должен включать типы файлов jpg, png и gif.


person mrpatg    schedule 08.08.2009    source источник
comment
Куча дубликатов: stackoverflow.com/questions/tagged/resize+php   -  person Andrew Moore    schedule 08.08.2009


Ответы (4)


Я предпочитаю библиотеку WideImage, потому что она действительно проста в использовании.

В вашем случае все, что вам нужно сделать, это:

$img_path = $_GET['img'];
$new_width = $_GET['width'];

$new_img = wiImage::load($img_path)->resize($new_width);

header('Content-Type: image/jpeg');

echo $new_img->asString('jpg', 80);

И он поддерживает jpeg, png, gif, gd, ...

person usoban    schedule 08.08.2009
comment
WideImage действительно хорош. Изменение размера изображения может оказаться довольно сложным, использование для этой задачи библиотеки, протестированной сообществом, - это хорошая вещь. :) - person deceze♦; 08.08.2009

Вы можете использовать библиотеку GD и создать простой скрипт, который будет масштабировать изображение по своему усмотрению. См. руководство

person RaYell    schedule 08.08.2009

не испытано

$file = $_GET('img');
$wid = $_GET('width');

// better ways to do this, but this works in a pinch
$orig = @imagecreatefromjpeg($file);
if ($orig === FALSE) $orig = @imagecreatefromgif($file);
if ($orig === FALSE) $orig = @imagecreatefrompng($file);
if ($orig === FALSE) exit("can't continue; $file is unreadable\n");

// aspect ratio stuff
$sx = imagesx($orig);
$sy = imagesy($orig);
$hyt = round($wid * $sy / $sx);

$img = imagecreatetruecolor($wid, $hyt);
imagecopyresampled($img, $orig, 0, 0, 0, 0, $wid, $hyt, $sx, $sy);
header('Content-type: image/jpeg');
imagejpeg($img);
person Scott Evernden    schedule 08.08.2009

Сохраните его как image.php, он должен работать так, как вы хотите.

<?php

if (array_key_exists('img', $_GET) === true)
{
    if (is_file($_GET['img']) === true)
    {
        $scale = array();

        $scale[] = (array_key_exists('width', $_GET) === true) ? $_GET['width'] : null;
        $scale[] = (array_key_exists('height', $_GET) === true) ? $_GET['height'] : null;

        Image($_GET['img'], implode('*', $scale));
    }
}

function Image($image, $scale = null)
{
    $type = image_type_to_extension(@exif_imagetype($image), false);

    if (function_exists('ImageCreateFrom' . $type) === true)
    {
        $image = call_user_func('ImageCreateFrom' . $type, $image);

        if (is_resource($image) === true)
        {
            $size = array(ImageSX($image), ImageSY($image));

            if (isset($scale) === true)
            {
                $scale = array_filter(explode('*', $scale), 'is_numeric');

                if (count($scale) >= 1)
                {
                    if (empty($scale[0]) === true)
                    {
                        $scale[0] = $scale[1] * $size[0] / $size[1];
                    }

                    else if (empty($scale[1]) === true)
                    {
                        $scale[1] = $scale[0] * $size[1] / $size[0];
                    }
                }

                else
                {
                    $scale = array($size[0], $size[1]);
                }
            }

            else
            {
                $scale = array($size[0], $size[1]);
            }

            $result = ImageCreateTrueColor($scale[0], $scale[1]);

            if (is_resource($result) === true)
            {
                ImageCopyResampled($result, $image, 0, 0, 0, 0, $scale[0], $scale[1], $size[0], $size[1]);

                if (headers_sent() === false)
                {
                    header('Content-Type: image/' . $type);

                    if ($type == 'gif')
                    {
                        return ImageGIF($result, null);
                    }

                    else if ($type == 'png')
                    {
                        return ImagePNG($result, null, 9);
                    }

                    else if ($type == 'jpeg')
                    {
                        return ImageJPEG($result, null, 90);
                    }
                }
            }
        }
    }

    return false;
}

?>
person Alix Axel    schedule 08.08.2009