调整图像大小并使每个图像适合平方纵横比(后端)

时间:2015-11-26 00:40:33

标签: php image

我对PHP和图像一般没有任何经验,但我需要在上传时将所有图像调整到正方形。

由于我有多个产品并且它们有不同尺寸的不同图片,我认为最好的方法是在上传过程中通过拍摄图像并将其“适合”到800x800白色方块中来“标准化”它们,同时保持纵横比(如果最长尺寸> 800则缩小尺寸,如果最长尺寸<800,则重新尺寸)。

我的初始解决方案是通过JavaScript创建的,我试图找到最大的图片并根据它调整所有其他图片的大小。虽然它不是很有用并且可能有问题,因为如果图像加载有延迟,可能无法加载图像以供JS执行操作,因此根本不显示图像。

$product = getProductById($productid);

$filesArray = array();


if (isset($_GET['files']) && $productid > 0) {
    $error = false;
    $files = array();
    $fileName = '';

    $uploaddir = "../images/products/";
    foreach ($_FILES as $file) {
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $random_name = $widgets->randomFileName();
        $randomFullFileName = $productid .'_'. $random_name . '.' . $ext;

        //copy to location
        //----------------
        //HERE I NEED TO CREATE A 800x800px SQUARE and fit the image into it
        //----------------
        if (move_uploaded_file($file['tmp_name'], $uploaddir . $randomFullFileName)) {

            //save to database
            $image_id = updateProduct('default_image', 'images/products/'.$randomFullFileName, $productid);

            if ($image_id > 0) {
                echo 'Added new image';
            } else {
                echo 'Error, unable to add. <br> Please try again.';
            }
        } else {
            echo 'Error, unable to add. <br> Please try again.';
        }
    }
}

之前:600x300 BEFORE

之后:带有白色边框的800x800填充空间 AFTER

2 个答案:

答案 0 :(得分:3)

您可以尝试这种方法(tested)。它可以使您的图像适合800x800方形画布,同时保持图像的纵横比。

resize_image():此功能将保持图像的宽高比。

function resize_image($img,$maxwidth,$maxheight) {
    //This function will return the specified dimension(width,height)
    //dimension[0] - width
    //dimension[1] - height

    $dimension = array();
    $imginfo = getimagesize($img);
    $imgwidth = $imginfo[0];
    $imgheight = $imginfo[1];
    if($imgwidth > $maxwidth){
        $ratio = $maxwidth/$imgwidth;
        $newwidth = round($imgwidth*$ratio);
        $newheight = round($imgheight*$ratio);
        if($newheight > $maxheight){
            $ratio = $maxheight/$newheight;
            $dimension[] = round($newwidth*$ratio);
            $dimension[] = round($newheight*$ratio);
            return $dimension;
        }else{
            $dimension[] = $newwidth;
            $dimension[] = $newheight;
            return $dimension;
        }
    }elseif($imgheight > $maxheight){
        $ratio = $maxheight/$imgheight;
        $newwidth = round($imgwidth*$ratio);
        $newheight = round($imgheight*$ratio);
        if($newwidth > $maxwidth){
            $ratio = $maxwidth/$newwidth;
            $dimension[] = round($newwidth*$ratio);
            $dimension[] = round($newheight*$ratio);
            return $dimension;
        }else{
            $dimension[] = $newwidth;
            $dimension[] = $newheight;
            return $dimension;
        }
    }else{
        $dimension[] = $imgwidth;
        $dimension[] = $imgheight;
        return $dimension;
    }
}

现在是你的代码,

$product = getProductById($productid);

$filesArray = array();


if (isset($_GET['files']) && $productid > 0) {
    $error = false;
    $files = array();
    $fileName = '';

    $uploaddir = "../images/products/";
    foreach ($_FILES as $file) {
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $random_name = $widgets->randomFileName();
        $randomFullFileName = $productid .'_'. $random_name . '.' . $ext;

        //copy to location
        //----------------
        //HERE I NEED TO CREATE A 800x800px SQUARE and fit the image into it


        // Create image from file
        $image = null;
        switch(strtolower($file['type']))
        {
            case 'image/jpeg':
                $image = imagecreatefromjpeg($file['tmp_name']);
                break;
            case 'image/png':
                $image = imagecreatefrompng($file['tmp_name']);
                break;
            case 'image/gif':
                $image = imagecreatefromgif($file['tmp_name']);
                break;
            default:
                exit('Unsupported type: '.$file['type']);
        }

        // Get current dimensions
        $old_width  = imagesx($image);
        $old_height = imagesy($image);

        // Get the new dimensions
        $dimension = resize_image($file, 800, 800);
        $new_width  = $dimension[0];
        $new_height = $dimension[1];

        // Create new empty image
        $new = imagecreatetruecolor($new_width, $new_height);

        // Resize old image into new
        imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);

        // Catch and save the image
        $status = false;
        switch(strtolower($file['type']))
        {
            case 'image/jpeg':
                $status = imagejpeg($new, $uploaddir . $randomFullFileName, 90);
                break;
            case 'image/png':
                $status = imagepng($new, $uploaddir . $randomFullFileName, 0);
                break;
            case 'image/gif':
                $status = imagegif($new, $uploaddir . $randomFullFileName);
                break;
        }

        // Destroy resources
        imagedestroy($image);
        imagedestroy($new);

        //save to database
        if($status){
            $image_id = updateProduct('default_image', 'images/products/'.$randomFullFileName, $productid);

            if ($image_id > 0) {
                echo 'Added new image';
            } else {
                echo 'Error, unable to add. <br> Please try again.';
            }
        }else{
            echo 'Error, unable to add. <br> Please try again.';
        }       

        //----------------
        //if (move_uploaded_file($file['tmp_name'], $uploaddir . $randomFullFileName)) {
        //    //save to database
        //    $image_id = updateProduct('default_image', 'images/products/'.$randomFullFileName, $productid);

        //    if ($image_id > 0) {
        //        echo 'Added new image';
        //    } else {
        //        echo 'Error, unable to add. <br> Please try again.';
        //    }
        //} else {
        //    echo 'Error, unable to add. <br> Please try again.';
        //}

    }
}

答案 1 :(得分:0)

原始答案

imagine怎么样?

//save to database评论之前插入此代码:

<?php
$imagine = new Imagine\Gd\Imagine();
$size = new Imagine\Image\Box(800, 800);
$mode = Imagine\Image\ImageInterface::THUMBNAIL_INSET;
$imagine
    ->open($uploaddir . $randomFullFileName)
    ->thumbnail($size, $mode)
    ->save($uploaddir . $randomFullFileName);

新答案

由于调整大小不能按预期工作(感谢@Pradeep Sanjaya),我会根据link的代码段粘贴解决方案:

/**
 * Image resize
 * @param string $input Full path to source image
 * @param string $output Full path to result image
 * @param int $width Width of result image
 * @param int $height Height of result image
 */
function resizeImage($input, $output, $width, $height)
{
    $imagine = new Imagine\Gd\Imagine();
    $size = new Imagine\Image\Box($width, $height);
    $mode = Imagine\Image\ImageInterface::THUMBNAIL_INSET;
    $resizeimg = $imagine
        ->open($input)
        ->thumbnail($size, $mode);
    $sizeR = $resizeimg->getSize();
    $widthR = $sizeR->getWidth();
    $heightR = $sizeR->getHeight();

    $preserve = $imagine->create($size);
    $startX = $startY = 0;
    if ($widthR < $width) {
        $startX = ($width - $widthR) / 2;
    }
    if ($heightR < $height) {
        $startY = ($height - $heightR) / 2;
    }
    $preserve
        ->paste($resizeimg, new Imagine\Image\Point($startX, $startY))
        ->save($output);
}

根据原始问题使用:

<?php
// placed after `save to database` comment
resizeImage(
    $uploaddir . $randomFullFileNamem,
    $uploaddir . $randomFullFileName,
    800, 800
);