在之前的文章《PHP中的===运算符为什么比==快?》中给大家介绍了PHP中的===运算符为什么比==快,感兴趣的朋友可以学习了解一下~

本文的主题则是教大家在PHP中调整JPEG图像大小。

我们在网站开发过程中,有时会遇到要求实现缩放图像的功能、比如封面图、缩略图、资料图等等。要根据需求规定图片的尺寸,不过大家应该也知道关于图像大小,我们可以用HTML来修改,如下:

<img src="001.jpg" height="100" width="100" alt="图片尺寸">
登录后复制

当然本文的重点是用 PHP 调整图像大小,下面我们就直接来看代码:

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);
登录后复制

效果如下:

4bbbb39c9cde5a3676ee4dd616a441d.png

这里就需要大家掌握一个重要函数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 相同的话)区域,但如果区域交迭的话则结果不可预知。

最后给大家推荐最新最全面的《PHP视频教程》~快来学习吧!

以上就是PHP也能调整JPEG图像大小!的详细内容,更多请关注悠悠之家其它相关文章!

点赞(38)

评论列表共有 0 条评论

立即
投稿
返回
顶部