search
HomeBackend DevelopmentPHP TutorialPHP gd2 uploads pictures/text watermarks/picture watermarks/proportional thumbnails/implementation code_PHP tutorial

Copy code The code is as follows:

//Upload file type list
$uptypes=array(
'image/jpg',
'image/jpeg',
'image /png',
'image/pjpeg',
'image/gif',
'image/bmp',
'image/x-png'
);
$ max_file_size = 200000; //Upload file size limit, unit BYTE
$path_im = "prod_img/"; //Generate large image saving folder path
$path_sim = "prod_simg/"; //Thumbnail image saving file Clip path
$watermark = 1; //Whether to add watermark (1 means adding watermark, others means not adding watermark);
$watertype = 1; //Watermark type (1 means text, 2 means picture)
$waterstring = "[url=http://www.jy17.com/]http://www.jy17.com/[/url]"; //Watermark string
$waterimg = "water. png"; //Watermark image file path
$waterclearly = 100; //Watermark transparency 0-100, smaller numbers are more transparent
$imclearly = 100; //Picture clarity 0-100, the larger the number, the clearer it is , the larger the file size
$simclearly = 75; //Thumbnail resolution 0-100, the larger the number, the clearer the file size, the larger the file size
$smallmark = 1; //Whether to generate a thumbnail (1 is plus Generate, others are not);
$dst_sw = 80; //Define the thumbnail width. I use equal proportion scaling for the height, so just compare the width.
?>

Upload file:



The file types allowed to be uploaded are:=implode(',',$uptypes)?>

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (!is_uploaded_file($_FILES["upfile"][tmp_name]))
//Does the file exist?
{
echo "The picture does not exist!";
exit;
}
$file = $_FILES["upfile"];
if($ max_file_size //Check file size
{ $max_file_size = $max_file_size/1000;
echo "The file is too large, exceeding ".$max_file_size." KB!" ;
exit;
}
if(!in_array($file["type"],$uptypes))
//Check file type
{
echo "File type does not match !".$file["type"];
exit;
}
if(!file_exists($path_im))
//Check whether the upload directory exists, if not create
{
mkdir($path_im);
}
if(!file_exists($path_sim))
//Check whether the thumbnail directory exists, if not create it
{
mkdir($ path_sim);
}
$filename = $file["tmp_name"];
$im_size = getimagesize($filename);
$src_w = $im_size[0];
$src_h = $im_size[1];
$src_type = $im_size[2];
$pinfo = pathinfo($file["name"]);
$filetype = $pinfo['extension'];
$all_path = $path_im.time().".".$filetype; //Path + file name, currently named after upload time
if (file_exists($all_path))
{
echo "The file with the same name already exists";
exit;
}
if(!move_uploaded_file ($filename,$all_path))
{
echo "Error moving file";
exit;
}
$pinfo = pathinfo($all_path);
$fname = $pinfo[basename];
echo "has been successfully uploaded
File name: ".$all_path."
";
echo "Width: ".$src_w."px ";
echo "Length:".$src_h."px ";
echo "
Size: ".$file["size"]." bytes";
switch($src_type)//Judgement source Image file type
{
case 1://gif
$src_im = imagecreatefromgif($all_path);//Get the image from the source image file
break;
case 2://jpg
$src_im = imagecreatefromjpeg($all_path);
break;
case 3://png
$src_im = imagecreatefrompng($all_path);
break;
//case 6 :
//$src_im=imagecreatefromwbmp($all_path);
//break;
default:
die("Unsupported file type");
exit;
}
if($watermark == 1)
{
//$iinfo = getimagesize($all_path,$iinfo);
$dst_im = imagecreatetruecolor($src_w,$src_h);
//Create a true color bitmap of the same size based on the original image size
$white = imagecolorallocate($dst_im,255,255,255);//White
//Fill the new image with the background color
$black = imagecolorallocate ($dst_im,0,0,0);//Black
$red = imagecolorallocate($dst_im,255,0,0);//Red
$orange = imagecolorallocate($dst_im,255,85, 0);//Orange
imagefill($dst_im,0,0,$white);
imagecopymerge($dst_im,$src_im,0,0,0,0,$src_w,$src_h,100); //The original image is written into the new true color bitmap
//imagefilledrectangle($dst_im,1,$src_h-15,80,$src_h,$white);
switch($watertype)
{
case 1: //Watermark string
imagestring($dst_im,5,5,$src_h-20,$waterstring,$orange);//Text watermark, font No. 5, color orange, located in the background The lower left corner of the picture
break;
case 2: //Watermark image
$lim_size = getimagesize($waterimg); //Get the watermark image size, information
switch($lim_size[2]) //Determine the watermark image file type
{
case 1://gif
$src_lim = imagecreatefromgif($waterimg); //Get the watermark image
break;
case 2:// jpg
$src_lim = imagecreatefromjpeg($waterimg);
break;
case 3://png
$src_lim = imagecreatefrompng($waterimg);
break;
//case 6:
//$src_im=imagecreatefromwbmp($waterimg);
//break;
default:
die("Unsupported file type");
exit;
}
$src_lw = ($src_w-$lim_size[0])/2; //The watermark is located at the width positioning in the center of the background image
$src_lh = ($src_h-$lim_size[1])/2; / /height positioning
imagecopymerge($dst_im,$src_lim,$src_lw,$src_lh,0,0,$lim_size[0],$lim_size[1],$waterclearly);// Merge two images and set watermark transparency $waterclearly
imagedestroy($src_lim);
break;
}
switch($src_type)
{
case 1:
imagegif($dst_im,$all_path,$ imclearly);//Generate gif files, image clarity 0-100
break;
case 2:
imagejpeg($dst_im,$all_path,$imclearly);//Generate jpg files, image clarity 0-100
break;
case 3:
imagepng($dst_im,$all_path,$imclearly);//Generate png file, image definition 0-100
break;
/ /case 6:
//imagewbmp($dst_im,$all_path);
break;
}
//Release cache
imagedestroy($dst_im);
}
if($smallmark == 1)
{
$sall_path = $path_sim.time().".".$filetype;
if (file_exists($sall_path))
{
echo "The file with the same name already exists";
exit;
}
if($src_w {
$ dst_sim = imagecreatetruecolor($src_w,$src_h); //Create a new thumbnail true color bitmap
imagecopymerge($dst_sim,$src_im,0,0,0,0,$src_w,$src_h,100); // The original image is written into the new true color bitmap
}
if($src_w > $dst_sw) // Original image size > Thumbnail size
{
$dst_sh = $dst_sw/ $src_w*$src_h;
$dst_sim = imagecreatetruecolor($dst_sw,$dst_sh); //Create a new thumbnail true color bitmap (reducing the original image size proportionally)
imagecopyresampled($dst_sim,$src_im,0 ,0,0,0,$dst_sw,$dst_sh,$src_w,$src_h); //The original image is written into the new true color bitmap
}
switch($src_type)
{
case 1:
imagegif($dst_sim,$sall_path,$simclearly);//Generate gif file, image resolution 0-100
break;
case 2:
imagejpeg($dst_sim ,$sall_path,$simclearly);//Generate jpg file, image resolution 0-100
break;
case 3:
imagepng($dst_sim,$sall_path,$simclearly);//Generate png File, image resolution 0-100
break;
//case 6:
//imagewbmp($dst_sim,$sall_path);
break;
}
//release Cache
imagedestroy($dst_sim);
}
//Release cache
imagedestroy($src_im);
}
?>

php Function 2 to generate thumbnails in equal proportions
Copy code The code is as follows:

function reSizeImg($imgSrc, $resize_width, $resize_height, $isCut=false) {
//Type of image
$type = substr ( strrchr ( $imgSrc, "." ), 1 );
//Initialize image
if ($type == "jpg") {
$im = imagecreatefromjpeg ( $imgSrc );
}
if ($type == "gif") {
$im = imagecreatefromgif ( $imgSrc );
}
if ($type == "png") {
$im = imagecreatefrompng ( $imgSrc );
}
//Target image address
$full_length = strlen ( $imgSrc );
$type_length = strlen ( $type );
$name_length = $full_length - $type_length;
$ name = substr ( $imgSrc, 0, $name_length - 1 );
$dstimg = $name . "_s." . $type;
$width = imagesx ( $im );
$height = imagesy ( $im );
//Generate image
//Changed image ratio
$resize_ratio = ($resize_width) / ($resize_height);
//Actual image The ratio of
$ratio = ($width) / ($height);
if (($isCut) == 1) //Cut image
{
if ($ratio >= $ resize_ratio) //High priority
{
$newimg = imagecreatetruecolor ( $resize_width, $resize_height );
imagecopyresampled ( $newimg, $im, 0, 0, 0, 0, $resize_width, $resize_height, (($height) * $resize_ratio), $height );
ImageJpeg ( $newimg, $dstimg );
}
if ($ratio {
$newimg = imagecreatetruecolor ( $resize_width, $resize_height );
imagecopyresampled ( $newimg, $im, 0, 0, 0, 0, $resize_width, $resize_height, $width, (($width) / $ resize_ratio) );
ImageJpeg ( $newimg, $dstimg );
}
} else //Do not crop the image
{
if ($ratio >= $resize_ratio) {
$newimg = imagecreatetruecolor ( $resize_width, ($resize_width) / $ratio );
imagecopyresampled ( $newimg, $im, 0, 0, 0, 0, $resize_width, ($resize_width) / $ratio, $width , $height );
ImageJpeg ( $newimg, $dstimg );
}
if ($ratio $newimg = imagecreatetruecolor ( ($resize_height) * $ratio, $resize_height );
imagecopyresampled ( $newimg, $im, 0, 0, 0, 0, ($resize_height) * $ratio, $resize_height, $width, $height );
ImageJpeg ( $newimg, $ dstimg );
}
}
ImageDestroy ( $im );
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321752.htmlTechArticleCopy the code as follows: ?php //Upload file type list $uptypes=array( 'image/jpg', 'image/jpeg', 'image/png', 'image/pjpeg', 'image/gif', 'image/bmp', 'image/x-png' ); $max_fi...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment