


PHP implements a method to automatically generate thumbnails based on url, url is automatically generated_PHP tutorial
php implements the method of automatically generating thumbnails based on url, and the url is automatically generated
The example in this article describes how PHP can automatically generate thumbnails based on URLs, which is a very practical function. Share it with everyone for your reference. The specific method is as follows:
Principle: Set apache rewrite, and when the image does not exist, call php to create the image.
For example:
The original image path is: http://localhost/upload/news/2013/07/21/1.jpg
The thumbnail path is: http://localhost/supload/news/2013/07/21/1.jpg
When accessing http://localhost/supload/news/2013/07/21/1.jpg, if the image exists, the image will be displayed. Otherwise, call createthumb.php to generate the image.
The directory structure is as follows:
www/PicThumb.class.php
www/ThumbConfig.php
www/upload/news/2013/07/21/1.jpg
www/upload/article/2013/07/21/2.jpg
www/supload/.htaccess
www/supload/watermark.png
www/supload/createthumb.php
http://localhost/ points to the www directory
Please check here for usage of PicThumb.class.php: http://www.bkjia.com/article/55530.htm
Need to enable apache rewrite:
sudo a2enmod rewrite
.htaccess file is as follows:
<IfModule mod_rewrite.c> RewriteEngine On # '-s' (is regular file, with size) # '-l' (is symbolic link) # '-d' (is directory) # 'ornext|OR' (or next condition) # 'nocase|NC' (no case) # 'last|L' (last rule) RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ createthumb.php?path=%{REQUEST_URI} [NC,L] </IfModule>
The createthumb.php file is as follows:
<?php define('WWW_PATH', dirname(dirname(__FILE__))); // 站点www目录 require(WWW_PATH.'/PicThumb.class.php'); // include PicThumb.class.php require(WWW_PATH.'/ThumbConfig.php'); // include ThumbConfig.php $logfile = WWW_PATH.'/createthumb.log'; // 日志文件 $source_path = WWW_PATH.'/upload/'; // 原路径 $dest_path = WWW_PATH.'/supload/'; // 目标路径 $path = isset($_GET['path'])? $_GET['path'] : ''; // 访问的图片URL // 检查path if(!$path){ exit(); } // 获取图片URI $relative_url = str_replace($dest_path, '', WWW_PATH.$path); // 获取type $type = substr($relative_url, 0, strpos($relative_url, '/')); // 获取config $config = isset($thumb_config[$type])? $thumb_config[$type] : ''; // 检查config if(!$config || !isset($config['fromdir'])){ exit(); } // 原图文件 $source = str_replace('/'.$type.'/', '/'.$config['fromdir'].'/', $source_path.$relative_url); // 目标文件 $dest = $dest_path.$relative_url; // 创建缩略图 $obj = new PicThumb($logfile); $obj->set_config($config); if($obj->create_thumb($source, $dest)){ ob_clean(); header('content-type:'.mime_content_type($dest)); exit(file_get_contents($dest)); } ?>
ThumbConfig.php file is as follows:
<?php $thumb_config = array( 'news' => array( 'fromdir' => 'news', // 来源目录 'type' => 'fit', 'width' => 100, 'height' => 100, 'bgcolor' => '#FF0000' ), 'news_1' => array( 'fromdir' => 'news', 'type' => 'fit', 'width' => 200, 'height' => 200, 'bgcolor' => '#FFFF00' ), 'article' => array( 'fromdir' => 'article', 'type' => 'crop', 'width' => 250, 'height' => 250, 'watermark' => WWW_PATH.'/supload/watermark.png' ) ); ?>
After accessing these three paths, thumbnails will be automatically generated according to config
http://localhost/supload/news/2013/07/21/1.jpg
http://localhost/supload/news_1/2013/07/21/1.jpg
http://localhost/supload/article/2013/07/21/2.jpg
Click here to download the complete code of the example described in this article.
I hope this article will be helpful to everyone’s PHP programming design.
The php environment needs to support the GD library.
$img_name=$_GET['img']; //Get query string
$src_img=imagecreatefromjpeg($img_name);
$ow=imagesx($src_img);
$oh=imagesy($src_img);
$desc_img=imagecreate(400,300);
imagecopyresized($desc_img,$src_img, 0,0,0,0,400,300,$ow,$oh);
imagejpeg($desc_img);
imagedestroy($desc_img);
imagedestroy($src_img);
?>
The above code can generate a 400*300 thumbnail based on an image, such as:
www.xx.com/image.php?img=1.jpg
Requirement 1.jpg must exist and the size is arbitrary. And 1.jpg and image.php are in the same directory.
www.xx.com/image.php?img=upload2009/1.jpg
Also, no need to change, just use the one above. Anyway, the $img_name variable is the URL of the image. You can change it yourself according to the actual situation.
Let me give you a function
// *****generate thumbnails*****
// Only consider jpg, png, gif formats
// $srcImgPath source image path
// $targetImgPath target image path
// $targetW target image width
// $targetH target image height
function makeThumbnail($srcImgPath,$targetImgPath,$targetW,$targetH )
{
$imgSize = GetImageSize($srcImgPath);
$imgType = $imgSize[2];
//@ Make the function not output error information to the page
switch ($imgType )
{
case 1:
$srcImg = @ImageCreateFromGIF($srcImgPath);
break;
case 2:
$srcImg = @ImageCreateFromJpeg($srcImgPath);
break;
case 3:
$srcImg = @ImageCreateFromPNG($srcImgPath);
break;
}
//Get the width and height of the source image
$srcW = ImageSX ($srcImg);
$srcH = ImageSY($srcImg);
if($srcW>$targetW || $srcH>$targetH)
{
$targetX = 0;
$targetY = 0;
if ($srcW > $srcH)
{
$finaW=$targetW;
$finalH=round($srcH*$finaW/$srcW);
$targetY=floor(($targetH-$finalH)/2);
}
else
{
$finalH=$targetH;
$finaW=round($srcW*$ finalH/$srcH);
$targetX=floor(($targetW-$finaW)/2);
}
//function_exists checks whether the function has been defined
//ImageCreateTrueColor This function requires GD2 .0.1 or higher version
if(function...the rest of the text>>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,
