dp518158 2015-11-26 00:40
浏览 255
已采纳

调整图像大小并将每个图像调整为方形保持纵横比(后端)

I don't have any experience with PHP and images in general, but I have a need to resize all images into the square when they get uploaded.

Since I have multiple products and they have different pictures that comes in different sizes, I think that the best approach is to 'standardize' them during the upload by taking an image and 'fitting' it into the 800x800 white square while maintaining the aspect ratio (if longest size >800 then downsize, if longest size <800, then re-size).

My initial solution was created via JavaScript, where I tried to find the biggest picture and resize all other images according to it. Although, it is not very useful and can be faulty since if there is a delay in image load, images might not be loaded for JS to perform the operation, thus not showing images at all.

$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.';
        }
    }
}

Before: 600x300 BEFORE

After: 800x800 with white borders to fill-in the space AFTER

  • 写回答

2条回答

  • dongqiang5865 2015-11-26 01:59
    关注

    You can try this approach (tested). It will fit your images into an 800x800 square canvas while maintaining the aspect ratio of your images.

    resize_image(): This function will maintain the aspect ratio of your 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;
        }
    }
    

    And now comes your code,

    $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条)

报告相同问题?

悬赏问题

  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B