Home  >  Article  >  Backend Development  >  How to modify image pixel size in php

How to modify image pixel size in php

藏色散人
藏色散人Original
2020-11-04 09:11:233070browse

php method to modify the pixel size of an image: first create a PHP sample file; then create a new image from the file or URL according to the suffix; then obtain the pixels of the current image to be modified; and finally resample and copy part of the image and adjust the size.

How to modify image pixel size in php

Recommended: "PHP Video Tutorial"

PHP Modify Image Pixel Size

The following are Methods and usage examples of 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);

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.

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

Statement:
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
Previous article:How to replace img in phpNext article:How to replace img in php