PHP first scales proportionally and then crops the image losslessly [example source code]

When many people use a program to crop a picture, they directly crop it on the original picture. The result of such cropping is that the picture becomes incomplete. The ideal way is to scale down the picture first, and then cut off the excess part, which will preserve the image. More picture information.

Implementation code:

<?php
 
/**
 * 说明:函数功能是把一个图像裁剪为任意大小的图像,图像不变形
 *
 * @param string $src_file   需要处理图片的文件名(绝对路径)
 * @param string $dst_file   生成新图片的保存文件名(绝对路径)
 * @param int    $new_width  生成新图片的宽
 * @param int    $new_height 生成新图片的高
 */
function my_image_resize($src_file, $dst_file, $new_width, $new_height){
    if ($new_width < 1 || $new_height < 1) {
        echo 'params width or height error !';
        die;
    }
    if (!file_exists($src_file)) {
        echo $src_file . ' is not exists !';
        die;
    }
 
    // 图像类型
    $type = exif_imagetype($src_file);
    $support_type = array(IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF);
    if (!in_array($type, $support_type, true)) {
        echo 'this type of image does not support! 

Guess you like

Origin blog.csdn.net/mo3408/article/details/132194401