Function code for generating thumbnails with the strongest compatibility in PHP (modified version)

Source: Internet
Author: User
Tags imagejpeg
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 );
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.