It is a headache to write a universal program to consider compatibility. There are a lot of code for generating thumbnails using PHP, but it is completely compatible with gd1.6 and gd2.x and can ensure that there is almost no clear code for shrinking images, I changed my previous code to implement it.
The code is as follows:
Function ImageResize ($ srcFile, $ toW, $ toH, $ toFile = "")
{
If ($ toFile = "") {$ toFile = $ srcFile ;}
$ Info = "";
$ Data = GetImageSize ($ srcFile, $ info );
Switch ($ data [2])
{
Case 1:
If (! Function_exists ("imagecreatefromgif ")){
Echo "your GD library cannot use images in GIF format. please use Jpeg or PNG format! Return ";
Exit ();
}
$ Im = ImageCreateFromGIF ($ srcFile );
Break;
Case 2:
If (! Function_exists ("imagecreatefromjpeg ")){
Echo "your GD library cannot use images in jpeg format. please use images in other formats! Return ";
Exit ();
}
$ 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 = $ ftoW * ($ srcH/$ srcW );
}
Else {
$ FtoH = $ toH;
$ FtoW = $ ftoH * ($ srcW/$ srcH );
}
If ($ srcW> $ toW | $ srcH> $ toH)
{
If (function_exists ("imagecreatetruecolor ")){
@ $ Ni = ImageCreateTrueColor ($ ftoW, $ ftoH );
If ($ ni) ImageCopyResampled ($ ni, $ im, 0, 0, 0, $ ftoW, $ ftoH, $ srcW, $ srcH );
Else {
$ Ni = ImageCreate ($ ftoW, $ ftoH );
ImageCopyResized ($ ni, $ im, 0, 0, 0, $ ftoW, $ ftoH, $ srcW, $ srcH );
}
} Else {
$ Ni = ImageCreate ($ ftoW, $ ftoH );
ImageCopyResized ($ ni, $ im, 0, 0, 0, $ ftoW, $ ftoH, $ srcW, $ srcH );
}
If (function_exists ('imagejpeg ') imagejpeg ($ ni, $ toFile );
Else ImagePNG ($ ni, $ toFile );
ImageDestroy ($ ni );
}
ImageDestroy ($ im );
}