php 生成二维码及图片尺寸转换

GD和图像处理(三)


摘要:根据字符串内容,生成二维码图片,及对图片尺寸进行转换。

1. 生成二维码图片:

  • 下载二维码生成类库
    https://sourceforge.net/projects/phpqrcode/

    下载后解压得到:phpqrcode.php,将其复制到自己的项目路径下即可。

  • 生成二维码图片

    require_once ‘./phpqrcode.php’;
    $str = ‘QTX just do it ! ‘;
    $file_path = ‘C:\Users\Administrator\Desktop\123445.png’; //要保存的路径文件名
    QRcode::png($str, $file_path, QR_ECLEVEL_M, 2, 0);
    string


2. 图片尺寸转换:

// 定义方法,可用以处理正方形图片或长方形图片尺寸,按宽高比例自适应
function resize($imgsrc, $width, $height = 0) {  //参数定义为:源图片,目标宽度,目标高度 
    $data = file_get_contents($imgsrc);
    $img_s = imagecreatefromstring($data);  // 获得源图片资源
    $width_s = imagesx($img_s);  // 获得源图片宽度
    $height_s = imagesy($img_s);  // 获得源图片高度

    $width_t = $width;  // 获得目标图片宽度
    $height_t = ($height == 0) ? $width : $height;  // 获得目标图片高度

    $image_t = imagecreatetruecolor($width_t, $height_t); //创建一个彩色的底图 
    $white = imagecolorallocate($image_t, 255, 255, 255);
    imagefill($image_t, 0, 0, $white); // 初始化背景为白色

    if (($width_s / $height_s) < ($width_t / $height_t)) {
        $_final['width'] = $width_s * $height_t / $height_s;
        $_final['height'] = $height_t;
        $dst['x'] = ($width_t - $_final['width']) / 2;
        $dst['y'] = 0;
    } else {
        $_final['width'] = $width_t;
        $_final['height'] = $width_t * $height_s / $width_s;
        $dst['x'] = 0;
        $dst['y'] = ($height_t - $_final['height']) / 2;
    }

    ImageCopyResized($image_t, $img_s, $dst['x'], $dst['y'], 0, 0, $_final['width'], $_final['height'], $width_s, $height_s);
    $rel = imagepng($image_t, $imgsrc);
    imagedestroy($img_s);
    imagedestroy($image_t);
    return $rel ? $imgsrc : false;
}

$result = resize($file_path, 100);
echo $result;
这里写图片描述



- 欢迎各大神点评 -




猜你喜欢

转载自blog.csdn.net/hqt_29/article/details/80678365