How to modify image pixels in php

藏色散人
Release: 2023-03-11 12:52:01
Original
2355 people have browsed it

php method to modify the image pixels: first create a PHP sample file; then modify the image pixel size through "function resize_image($filename, $newx, $newy, $ext){...}" .

How to modify image pixels in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

PHP changes the pixel size of the picture

The following are methods and usage examples for modifying images to specified pixels:

/**
 * @Desc:
 * @DateTime: xxx
 * @param $filename 文件名(所在路径)
 * @param $xmax 修改后最大宽度
 * @param $ymax 修改后最大高度
 * @param $ext 文件后缀
 * @return resource
 */
function resize_image($filename, $newx, $newy, $ext)
{
    //根据后缀,由文件或 URL 创建一个新图象(内置函数)
    if($ext == "jpg" || $ext == "jpeg")
        $im = imagecreatefromjpeg($filename);
    elseif($ext == "png")
        $im = imagecreatefrompng($filename);
    elseif($ext == "gif")
        $im = imagecreatefromgif($filename);
    //获取当前待修改图片像素(内置函数)
    $x = imagesx($im);
    $y = imagesy($im);
    //新建一个真彩色图像(内置函数)
    $im2 = imagecreatetruecolor($newx, $newy);
    
    //重采样拷贝部分图像并调整大小(内置函数)
    imagecopyresampled($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
    return $im2;
}
//使用示例:
$tmp = './img/test.jpg';//图片文件所在路径,相对路径和绝对路径都行
$fileinfo = pathinfo($tmp);
$ext = $fileinfo['extension'];
$image = resize_image($tmp, 1242, 2208, $ext);
if($ext == "jpg" || $ext == "jpeg")
    imagejpeg($image, $tmp);
elseif($ext == "png")
    imagepng($image, $tmp);
elseif($ext == "gif")
    imagegif($image, $tmp);
Copy after login

After the script is executed, the original image will be replaced with the modified image. The implementation logic can be reasonably modified according to the business.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to modify image pixels in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template