Home >Backend Development >PHP Tutorial >Detailed usage of creating high-definition thumbnails in php_PHP tutorial
php tutorial to create high-definition thumbnails and detailed usage
1. Use imagecreatetruecolor and imagecopyresampled functions to replace imagecreate and imagecopyresized respectively
2. Add 100 to the third parameter of imagejpeg (example: imagejpeg($ni,$tofile,100))
imagecreatetruecolor -- Create a new true color image
Description
resource imagecreatetruecolor (int x_size, int y_size)
imagecreatetruecolor() returns an image identifier representing a black image of size x_size and y_size
*/
header ("content-type: image/png");
$im = @imagecreatetruecolor (50, 100)
or die ("cannot initialize new gd image stream");
$text_color = imagecolorallocate ($im, 233, 14, 91);
imagestring ($im, 1, 5, 5, "a simple text string", $text_color);
imagepng ($im);
imagedestroy ($im);/*
If the ordinary imagecreate() function is used, the image quality will be distorted. I searched the Internet for a solution. The method is to replace the imagecreate() function with the imagecreateruecolor() function.
*/
function createpreview($img,$name,$path,$maxwidth,$maxheight,$quality){//image, save name, save path, maximum width, maximum height, quality
$widthratio=0;
$heightratio=0;
$width=imagesx($img);
$height=imagesy($img);
//Start calculating the reduction ratio
if($width>$maxwidth||$height>$maxheight){
if($width>$maxwidth){
$widthratio=$maxwidth/$width;
}
if($height>$maxheight){
$heightratio=$maxheight/$height;
}
if($widthratio>0&&$heightratio>0){
if($widthratio<$heightratio){
$ratio=$widthratio;
}else{
$ratio=$heightratio;
}
}elseif($widthratio>0){
$ratio=$widthratio;
}elseif($heightratio>0){
$ratio=$heightratio;
}
//Recalculate the width and height of the thumbnail based on the obtained ratio
$newwidth=$ratio*$width;
$newheight=$ratio*$height;
$newimg=imagecreatetruecolor($newwidth,$newheight); // Create target image
imagecopyresized($newimg,$img,0,0,0,0,$newwidth,$newheight,$width,$height);
imagejpeg($newimg,$path."s_".$name,$quality);
imagedestroy($newimg);
}else{
imagejpeg($img,$path."s_".$name,$quality);
}
}
/*
imagecopyresamples(), the image edges obtained by its pixel interpolation algorithm are smoother and of better quality (but the speed of this function is slower than imagecopyresized()).