PHP也能调整JPEG图像大小
我们在网站开发过程中,有时会遇到要求实现缩放图像的功能、比如封面图、缩略图、资料图等等。要根据需求规定图片的尺寸,不过大家应该也知道关于图像大小,我们可以用HTML来修改,如下:
<img src="https://www.swvq.com/001.jpg" alt="图片尺寸">
PHP代码如下:
<?php
$filename = '001.jpg';
// 最大宽度和高度
$width = 100;
$height = 100;
// 文件类型
header('Content-Type: image/jpg');
// 新尺寸
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// 重采样的图像
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0,
$width, $height, $width_orig, $height_orig);
// 输出图像
imagejpeg($image_p, null, 100);
效果如下:
这里就需要大家掌握一个重要函数imagecopyresampled()
:
(该函数适用版本PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)
imagecopyresampled
— 重采样拷贝部分图像并调整大小;
语法:
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
): bool
参数分别表示:
dst_image:目标图象资源。
src_image:源图象资源。
dst_x:目标 X 坐标点。
dst_y:目标 Y 坐标点。
src_x:源的 X 坐标点。
src_y:源的 Y 坐标点。
dst_w:目标宽度。
dst_h:目标高度。
src_w:源图象的宽度。
src_h:源图象的高度。
imagecopyresampled() 将一幅图像中的一块正方形区域拷贝到另一个图像中,平滑地插入像素值,因此,尤其是,减小了图像的大小而仍然保持了极大的清晰度。
In other words, imagecopyresampled() will take a rectangular area from src_image of width src_w and height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x,dst_y).
如果源和目标的宽度和高度不同,则会进行相应的图像收缩和拉伸。坐标指的是左上角。本函数可用来在同一幅图内部拷贝(如果 dst_image 和 src_image 相同的话)区域,但如果区域交迭的话则结果不可预知。
本文出至:学新通
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通
- 本文地址: https://www.swvq.com/boutique/detail/15651
- 联系方式: luke.wu@swvq.com
- 来源链接: www.php.cn/php-weizijiaocheng-481374.html
系列文章
更多
同类精品
更多
精彩评论
-
windows上查看nginx是否启动
PHP中文网 04-19 -
2023年最新的28道PHP面试题附答案
PHP中文网 03-27 -
docker hub 进不去怎么办
PHP中文网 03-15 -
推荐五款xml编辑工具
PHP中文网 03-04 -
navicat怎样清除注册表
PHP中文网 04-05 -
强力推荐10款好看使用的Bootstrap后台管理系统模板
PHP中文网 03-09 -
ChatGPT应用通过Axios+EventSource使用GPT3.5 API
uWydnA 03-13 -
vscode怎么调整代码大小两种方法
PHP中文网 03-11 -
navicat删除的数据能还原吗
PHP中文网 04-09 -
mysql,navicat怎么设置主键自增
PHP中文网 04-08