• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

PHP也能调整JPEG图像大小

武飞扬头像
PHP中文网
帮助13

我们在网站开发过程中,有时会遇到要求实现缩放图像的功能、比如封面图、缩略图、资料图等等。要根据需求规定图片的尺寸,不过大家应该也知道关于图像大小,我们可以用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小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tangbghgb
系列文章
更多 icon
同类精品
更多 icon
继续加载