PHP图片裁剪与缩放 / 无损裁剪图片

图片太大且规格不统一,显示的控制需要靠JavaScript来完成,用在移动设备上时显示效果不好且流量巨大,需要对现有图片库的图片进行一次处理,生成符合移动设备用的缩略图,将原来客户端JS做的工作转移到服务器端用PHP的GD库来集中处理。

图片源与需要的大小:

1 $src_img "wallpaper.jpg";
2 $dst_w = 300;
3 $dst_h = 200;

剪裁图像,保证图像区域最大化显示,并按比例缩放到指定大小

一开始采用了 imagecopyresized 方法进行图像等比缩小,实际操作后发现,图像缩小后燥点非常严重。后再换用 imagecopysampled 方法,该方法会对图像进行重新采样,对缩小的图像进行平滑处理,使清晰度得到很大提高。

01 <?
02 list($src_w,$src_h)=getimagesize($src_img);  // 获取原图尺寸
03  
04 $dst_scale $dst_h/$dst_w//目标图像长宽比
05 $src_scale $src_h/$src_w// 原图长宽比
06  
07 if ($src_scale>=$dst_scale){  // 过高
08     $w intval($src_w);
09     $h intval($dst_scale*$w);
10  
11     $x = 0;
12     $y = ($src_h $h)/3;
13 else // 过宽
14     $h intval($src_h);
15     $w intval($h/$dst_scale);
16  
17     $x = ($src_w $w)/2;
18     $y = 0;
19 }
20  
21 // 剪裁
22 $source=imagecreatefromjpeg($src_img);
23 $croped=imagecreatetruecolor($w$h);
24 imagecopy($croped$source, 0, 0, $x$y$src_w$src_h);
25  
26 // 缩放
27 $scale $dst_w $w;
28 $target = imagecreatetruecolor($dst_w$dst_h);
29 $final_w intval($w $scale);
30 $final_h intval($h $scale);
31 imagecopyresampled($target$croped, 0, 0, 0, 0, $final_w,$final_h$w$h);
32  
33 // 保存
34 $timestamp = time();
35 imagejpeg($target"$timestamp.jpg");
36 imagedestroy($target);

无损裁剪图片

上传图片的时候, 经常是不确定比例, 显示的时候又得统一, 这个方案可以解决

01 <?php
02 $image "jiequ.jpg"// 原图
03 $imgstream file_get_contents($image);
04 $im = imagecreatefromstring($imgstream);
05 $x = imagesx($im);//获取图片的宽
06 $y = imagesy($im);//获取图片的高
07  
08 // 缩略后的大小
09 $xx = 140;
10 $yy = 200;
11  
12 if($x>$y){
13 //图片宽大于高
14     $sx abs(($y-$x)/2);
15     $sy = 0;
16     $thumbw $y;
17     $thumbh $y;
18 else {
19 //图片高大于等于宽
20     $sy abs(($x-$y)/2.5);
21     $sx = 0;
22     $thumbw $x;
23     $thumbh $x;
24   }
25 if(function_exists("imagecreatetruecolor")) {
26   $dim = imagecreatetruecolor($yy$xx); // 创建目标图gd2
27 else {
28   $dim = imagecreate($yy$xx); // 创建目标图gd1
29 }
30 imageCopyreSampled ($dim,$im,0,0,$sx,$sy,$yy,$xx,$thumbw,$thumbh);
31 header ("Content-type: image/jpeg");
32 imagejpeg ($dim, false, 100);
33 ?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值