欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

缩放图片

程序员文章站 2024-03-24 12:20:16
...
      //使用前还需要在上传图片时对图片大小,尺寸做出限制
 // ini_set("memory_limit","20 M"); 图片达到2 M 的话    
   /**
     * 新建裁剪缩略图
     * @param
     *
     * @return int flag 0-缩放失败,1-成功,2-不需缩放,3-不需要缩放
     * ini_set("memory_limit","20 M"); 图片过大的话
     */
    public static function processImageCreate($oldWidth, $oldHeight, $newWidth, $newHeight, $srcImage, $newImgName, $cut=false) {
        $thumb_y = 0;
        $thumb_x = 0;
        //是否需要缩放
        if ($oldWidth > $newWidth || $oldHeight > $newHeight) {
            // 裁剪
            if ($cut) {
                //按小的边缩放
                if ($oldWidth < $oldHeight) {
                    $thumbWidth = $newWidth;
                    $thumbHeight = $oldHeight * $newWidth / $oldWidth;
                    // 裁剪
                    if ($thumbHeight > $newHeight) {
                        //$thumb_y        = -($thumbHeight - $newHeight)/2;

                    } else {
                        $thumbHeight = $newHeight;
                        $thumbWidth = $oldWidth * $newHeight / $oldHeight;
                        //$newHeight = $thumbHeight;
                    }
                } else {
                    $thumbHeight = $newHeight;
                    $thumbWidth = $oldWidth * $newHeight / $oldHeight;
                    if ($thumbWidth > $newWidth) {
                        //$thumb_x = -($thumbWidth - $newWidth) / 2;
                    } else {
                        $thumbWidth = $newWidth;
                        $thumbHeight = $oldHeight * $newWidth / $oldWidth;
                        //$newWidth = $thumbWidth;
                    }
                }

                // 仅缩放
            } else {
                if ($oldWidth > $oldHeight) {
                    $thumbWidth = $newWidth;
                    $thumbHeight = $oldHeight * $newWidth / $oldWidth;
                    $newHeight = $thumbHeight;
                } else {
                    $thumbHeight = $newHeight;
                    $thumbWidth = $oldWidth * $newHeight / $oldHeight;
                    $newWidth = $thumbWidth;
                }
            }

            // 新建空图片
            $thumb = imagecreatetruecolor($newWidth, $newHeight);
            // 组合新图片
            @imagecopyresampled($thumb, $srcImage, $thumb_x, $thumb_y, 0, 0, $thumbWidth, $thumbHeight, $oldWidth, $oldHeight);
            if (!imagejpeg($thumb, $newImgName, 100)) {
                $flag = 0;
            } else {
                $flag = 1;
            }
        } else if ($oldWidth == $newWidth || $oldHeight == $newHeight) {
            $flag = 2;
        } else {
            $flag = 3;
        }
        return $flag;
    }