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

来源:互联网 发布:天刀优化补丁 编辑:程序博客网 时间:2024/05/16 11:13

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

图片源与需要的大小:

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

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

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

01<?
02list($src_w,$src_h)=getimagesize($src_img);  // 获取原图尺寸
03 
04$dst_scale $dst_h/$dst_w//目标图像长宽比
05$src_scale $src_h/$src_w// 原图长宽比
06 
07if ($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;
13else // 过宽
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);
24imagecopy($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);
31imagecopyresampled($target$croped, 0, 0, 0, 0, $final_w,$final_h$w$h);
32 
33// 保存
34$timestamp = time();
35imagejpeg($target"$timestamp.jpg");
36imagedestroy($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 
12if($x>$y){
13//图片宽大于高
14    $sx abs(($y-$x)/2);
15    $sy = 0;
16    $thumbw $y;
17    $thumbh $y;
18else {
19//图片高大于等于宽
20    $sy abs(($x-$y)/2.5);
21    $sx = 0;
22    $thumbw $x;
23    $thumbh $x;
24  }
25if(function_exists("imagecreatetruecolor")) {
26  $dim = imagecreatetruecolor($yy$xx); // 创建目标图gd2
27else {
28  $dim = imagecreate($yy$xx); // 创建目标图gd1
29}
30imageCopyreSampled ($dim,$im,0,0,$sx,$sy,$yy,$xx,$thumbw,$thumbh);
31header ("Content-type: image/jpeg");
32imagejpeg ($dim, false, 100);
33?>
0 0
原创粉丝点击