PHP 实现图片等比例缩略图

PHP 实现图片等比例缩略图,生成正方形缩略图。

步骤:待压缩正方形图片的边长为原始图片宽度和高度的像素最小值,图片宽高较长的一边裁剪中间部分,再实现像素压缩。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php

$imgpath = 'test.jpg';

if (!empty($imgpath)) {
$info = getImageInfo($imgpath);
if ($info) {
$srcWidth = $info['width'];
$srcHeight = $info['height'];
if ($srcWidth < $srcHeight) {
$srcSize = $srcWidth;
$srcX = 0;
$srcY = ($srcHeight - $srcWidth) / 2;
} else {
$srcSize = $srcHeight;
$srcX = ($srcWidth - $srcHeight) / 2;
$srcY = 0;
}
$type = strtolower(empty($type) ? $info['type'] : $type);
unset($info);

//构造函数
$loadImage = 'imagecreatefrom'.($type=='jpg'?'jpeg':$type);
$createImage = 'image'.($type=='jpg'?'jpeg':$type);

//参数
$quality = 60;
$thumb_size = 200;

//载入原图
$src_image = $loadImage($imgpath);

//创建目标图
$thumb_image = imagecreatetruecolor($thumb_size, $thumb_size);
$color = imagecolorallocatealpha($thumb_image, 255, 255, 255, 100);
imagefill($thumb_image, 0, 0, $color);

//处理
//bool imagecopyresampled(resource $dst_image, resource $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h)
$result = imagecopyresampled($thumb_image, $src_image, 0, 0, $srcX, $srcY, $thumb_size, $thumb_size, $srcSize, $srcSize);

//生成图片
$index = strpos($imgpath, '.', 0);
$thumb_imgpath = substr($imgpath, 0, $index) . "-thumb" . substr($imgpath, $index);
$createImage($thumb_image, $thumb_imgpath, 100);

//释放资源
imagedestroy($src_image);
imagedestroy($thumb_image);
}
}

function getImageInfo($imgpath) {
$info = array();
$imageInfo = getimagesize($imgpath);
if($imageInfo !== false) {
$imageType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));
$imageSize = filesize($imgpath);
$info['width'] = $imageInfo[0];
$info['height'] = $imageInfo[1];
$info['type'] = $imageType;
$info['size'] = $imageSize;
$info['mime'] = $imageInfo['mime'];
}
return $info;
}

?>

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :