php 裁剪圖片並處理png圖片背景變黑


/*TODO 圖片裁剪*/
function img_cutting($file_old,$file_new,$h,$w){
    $image = $file_old; // 原圖
    $dir = 'xxxxxx';//新地址
    if(!is_dir($dir)){
        mkdir($dir,0777,true);
    }
    $imgstream = file_get_contents($image);
    $im = imagecreatefromstring($imgstream);
    $x = imagesx($im);//獲取圖片的寬
    $y = imagesy($im);//獲取圖片的高
// 縮略后的大小
    $xx = $h;
    $yy = $w;

    if($x>$y){
//圖片寬大於高
        $sx = abs(($y-$x)/2);
        $sy = 0;
        $thumbw = $y;
        $thumbh = $y;
    } else {
//圖片高大於等於寬
        $sy = abs(($x-$y)/2.5);
        $sx = 0;
        $thumbw = $x;
        $thumbh = $x;
    }
    $img_info= getimagesize($file_old);
    if(end($img_info) == 'image/png'){
        $img = imagecreatefrompng($file_old);
        imagesavealpha($img,true);//這里很重要;
        if(function_exists("imagecreatetruecolor")) {
            $dim = imagecreatetruecolor($yy, $xx); // 創建目標圖gd2
        } else {
            $dim = imagecreate($yy, $xx); // 創建目標圖gd1
        }
        imagealphablending($dim,false);//這里很重要,意思是不合並顏色,直接用$img圖像顏色替換,包括透明色;
        imagesavealpha($dim,true);//這里很重要,意思是不要丟了$thumb圖像的透明色;
        imageCopyreSampled ($dim,$im,0,0,$sx,$sy,$yy,$xx,$thumbw,$thumbh);
        return imagepng($dim,$file_new);
    }elseif(end($img_info) != 'image/gif'){
        if(function_exists("imagecreatetruecolor")) {
            $dim = imagecreatetruecolor($yy, $xx); // 創建目標圖gd2
        } else {
            $dim = imagecreate($yy, $xx); // 創建目標圖gd1
        }
        imageCopyreSampled ($dim,$im,0,0,$sx,$sy,$yy,$xx,$thumbw,$thumbh);
        return imagejpeg($dim,$file_new,100);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM