Home > Backend Development > PHP Tutorial > How to create compressed images in PHP

How to create compressed images in PHP

墨辰丷
Release: 2023-03-29 08:20:02
Original
1412 people have browsed it

This article mainly introduces the method of creating compressed images in PHP. The function of compressing images is implemented through custom functions. It involves skills related to reading PHP images and creating graphic images. Friends in need can refer to the following

The details are as follows:


<?php
//创建压缩图
function _create_thumbnail($srcFile, $toW, $toH, $toFile="")
{
  if ($toFile == "")
  {
    $toFile = $srcFile;
  }
  $info = "";
  $data = getimagesize($srcFile, $info);
  if (!$data)
    return false;
  //将文件载入到资源变量im中
  switch ($data[2])
  {
    case 1:
      $im = imagecreatefromgif($srcFile);
      break;
    case 2:
      $im = imagecreatefromjpeg($srcFile);
      break;
    case 3:
      $im = imagecreatefrompng($srcFile);
      break;
  }
  //计算缩略图的宽高
  $srcW = imagesx($im);
  $srcH = imagesy($im);
  $toWH = $toW / $toH;
  $srcWH = $srcW / $srcH;
  if ($toWH <= $srcWH)
  {
    $ftoW = $toW;
    $ftoH = (int)($ftoW * ($srcH / $srcW));
  }
  else
  {
    $ftoH = $toH;
    $ftoW = (int)($ftoH * ($srcW / $srcH));
  }
  if (function_exists("imagecreatetruecolor"))
  {
    $ni = imagecreatetruecolor($ftoW, $ftoH); //新建一个真彩色图像
    if ($ni)
    {
      //重采样拷贝部分图像并调整大小 可保持较好的清晰度
      imagecopyresampled($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH);
    }
    else
    {
      //拷贝部分图像并调整大小
      $ni = imagecreate($ftoW, $ftoH);
      imagecopyresized($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH);
    }
  }
  else
  {
    $ni = imagecreate($ftoW, $ftoH);
    imagecopyresized($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH);
  }
  //保存到文件 统一为.png格式
  imagepng($ni, $toFile); //以 PNG 格式将图像输出到浏览器或文件
  ImageDestroy($ni);
  ImageDestroy($im);
}
?>
Copy after login



##Summary: The above is the entire content of this article , I hope it can be helpful to everyone’s study.

Related recommendations:

phpDetailed explanation of WeChat public platform interaction and interface

## php Detailed explanation of file upload

##php

WeChat public account js-sdk development application


The above is the detailed content of How to create compressed images in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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