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);
    }

 

转载于:https://www.cnblogs.com/5aiQ/p/10028906.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值