src/Services/Common/ImageTools.php line 32

Open in your IDE?
  1. <?php
  2. //----------------------------------------------------------------------
  3. // src/Services/Common/ImageTools.php
  4. //----------------------------------------------------------------------
  5. namespace App\Services\Common;
  6. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  7. use Symfony\Component\Security\Core\Security;
  8. use Doctrine\Persistence\ManagerRegistry;
  9. use App\Entity\Access;
  10. use App\Entity\SocietyGroup;
  11. use App\Entity\Client\Individual;
  12. use App\Entity\Client\Store;
  13. use App\Entity\Common\Attachment;
  14. use App\Entity\Common\Image;
  15. use App\Entity\Common\MimeType;
  16. use App\Entity\Config\Config;
  17. use App\Entity\Equipment\Equipment;
  18. use App\Entity\HR\HumanResource;
  19. use App\Entity\Media\Article;
  20. use App\Entity\Mission\Mission;
  21. use App\Entity\Platform\Society;
  22. use App\Entity\Product\Product;
  23. use App\Services\LogTools;
  24. class ImageTools
  25. {
  26.     public function __construct(ManagerRegistry $doctrineLogTools $logToolsUrlGeneratorInterface $routerSecurity $security)
  27.     {
  28.         $this->em $doctrine->getManager();
  29.         $this->logTools $logTools;
  30.         $this->security $security;
  31.         $this->router $router;
  32.     }
  33.     public function getQuestionMarkLogo()
  34.     {
  35.         return "assets/custom_society_group_icons/question-mark.png";
  36.     }
  37.     public function getRequiredParamsForForm()
  38.     {
  39.         // Get Accepted MimeTypes
  40.         $mimeTypes $this->getActiveImageMimeTypes();
  41.         // ... and extensions for display
  42.         $allowedExtensions $this->getActiveImageExtensionsAsString();
  43.         // Get the max file size allowed
  44.         $filesize $this->em->getRepository(Config::class)->findOneByName(Config::DEFAULT_UPLOAD_MAX_FILE_SIZE);
  45.         if ($filesize === null)
  46.         {
  47.             // This should not happen
  48.             $this->logTools->errorlog("Config::DEFAULT_UPLOAD_MAX_FILE_SIZE not found");
  49.             $filesize 512 "M";
  50.         }
  51.         else
  52.         {
  53.             $filesize $filesize->getValue()."M";
  54.         }
  55.         return array(
  56.             'filesize'            =>    $filesize,
  57.             'mimeTypes'            =>    $mimeTypes,
  58.             'allowedExtensions'    =>    $allowedExtensions,
  59.         );
  60.     }
  61.     public function getActiveMimeTypes()
  62.     {
  63.         $objects $this->em->getRepository(MimeType::class)
  64.             ->findBy(array(
  65.                 'isActive'        =>    1,
  66.             ), array(
  67.                 'mime'            =>    'asc',
  68.             ));
  69.         $output = array();
  70.         foreach ($objects as $object)
  71.         {
  72.             $output[] = $object->getMime();
  73.         }
  74.         return $output;
  75.     }
  76.     public function getActiveImageMimeTypes()
  77.     {
  78.         $objects $this->em->getRepository(MimeType::class)
  79.             ->findBy(array(
  80.                 'isActive'        =>    1,
  81.                 'isImage'        =>    1,
  82.             ), array(
  83.                 'mime'            =>    'asc',
  84.             ));
  85.         $output = array();
  86.         foreach ($objects as $object)
  87.         {
  88.             $output[] = $object->getMime();
  89.         }
  90.         return $output;
  91.     }
  92.     public function getActiveExtensions()
  93.     {
  94.         $objects $this->em->getRepository(MimeType::class)
  95.             ->findBy(array(
  96.                 'isActive'        =>    1,
  97.             ), array(
  98.                 'mime'            =>    'asc',
  99.             ));
  100.         $output = array();
  101.         foreach ($objects as $object)
  102.         {
  103.             $output[] = $object->getExtension();
  104.         }
  105.         return $output;
  106.     }
  107.     public function getActiveImageExtensions()
  108.     {
  109.         $objects $this->em->getRepository(MimeType::class)
  110.             ->findBy(array(
  111.                 'isActive'        =>    1,
  112.                 'isImage'        =>    1,
  113.             ), array(
  114.                 'mime'            =>    'asc',
  115.             ));
  116.         $output = array();
  117.         foreach ($objects as $object)
  118.         {
  119.             $output[] = $object->getExtension();
  120.         }
  121.         return $output;
  122.     }
  123.     public function getActiveExtensionsAsString()
  124.     {
  125.         $objects $this->em->getRepository(MimeType::class)
  126.             ->findBy(array(
  127.                 'isActive'        =>    1,
  128.             ), array(
  129.                 'mime'            =>    'asc',
  130.             ));
  131.         $output "";
  132.         foreach ($objects as $object)
  133.         {
  134.             $output .= $object->getExtension();
  135.             $output .= ", ";
  136.         }
  137.         if ($output != "")
  138.         {
  139.             $output substr($output,0,-1);
  140.             $output substr($output,0,-1);
  141.         }
  142.         return $output;
  143.     }
  144.     public function getActiveImageExtensionsAsString()
  145.     {
  146.         $objects $this->em->getRepository(MimeType::class)
  147.             ->findBy(array(
  148.                 'isActive'        =>    1,
  149.                 'isImage'        =>    1,
  150.             ), array(
  151.                 'mime'            =>    'asc',
  152.             ));
  153.         $output "";
  154.         foreach ($objects as $object)
  155.         {
  156.             $output .= $object->getExtension();
  157.             $output .= ", ";
  158.         }
  159.         if ($output != "")
  160.         {
  161.             $output substr($output,0,-1);
  162.             $output substr($output,0,-1);
  163.         }
  164.         return $output;
  165.     }
  166.     public function getProfilePathForSocietyGroup(SocietyGroup $group$quality 0)
  167.     {
  168.         if ($group->getLogo() !== null)
  169.         {
  170.             return $group->getLogo()->getUrlForDisplay($quality);
  171.         }
  172.         $logoPath $this->getDefaultCameraPathForQuality($quality);
  173.         return $logoPath->getValue();
  174.     }
  175.     public function getLogoPathForSocietyGroup(SocietyGroup $societyGroup$quality 0)
  176.     {
  177.         if ($societyGroup->getLogo() !== null)
  178.         {
  179.             return $societyGroup->getLogo()->getUrlForDisplay($quality);
  180.         }
  181.         $logoPath $this->getDefaultCameraPathForQuality($quality);
  182.         return $logoPath->getValue();
  183.     }
  184.     public function getPhpLogoPathForSociety(Society $society$quality 0)
  185.     {
  186.         if ($society->getLogo() !== null)
  187.         {
  188.             return $society->getLogo()->getPhpPath($quality);
  189.         }
  190.         if ($society->getGroup() !== null && $society->getGroup()->getLogo() !== null)
  191.         {
  192.             return $society->getGroup()->getLogo()->getPhpPath($quality);
  193.         }
  194.         $logoPath $this->getDefaultCameraPathForQuality($quality);
  195.         return $logoPath->getValue();
  196.     }
  197.     public function getLogoPathForSociety(Society $society$quality 0)
  198.     {
  199.         if ($society->getLogo() !== null)
  200.         {
  201.             return $society->getLogo()->getUrlForDisplay($quality);
  202.         }
  203.         if ($society->getGroup() !== null && $society->getGroup()->getLogo() !== null)
  204.         {
  205.             return $society->getGroup()->getLogo()->getUrlForDisplay($quality);
  206.         }
  207.         $logoPath $this->getDefaultCameraPathForQuality($quality);
  208.         return $logoPath->getValue();
  209.     }
  210.     public function getProfilePathForHumanResource(HumanResource $humanResource$quality 0)
  211.     {
  212.         if ($humanResource->getProfileImage() !== null)
  213.             return $humanResource->getProfileImage()->getUrlForDisplay($quality);
  214.         //$logoPath = $this->getDefaultCameraPathForQuality($quality);
  215.         $logoPath $this->getDefaultPathForHumanResource($quality);
  216.         return $logoPath->getValue();
  217.     }
  218.     public function getProfilePathForStore(Store $store$quality 0)
  219.     {
  220.         if ($store->getLogo() !== null)
  221.             return $store->getLogo()->getUrlForDisplay($quality);
  222.         $logoPath $this->getDefaultCameraPathForQuality($quality);
  223.         return $logoPath->getValue();
  224.     }
  225.     public function getProfilePathForClient($client$quality)
  226.     {
  227.         if ($client !== null)
  228.         {
  229.             if ($client->getIndividual() !== null)
  230.                 return $this->getProfilePathForIndividual($client->getIndividual(), $quality);
  231.             if ($client->getStore() !== null)
  232.                 return $this->getProfilePathForStore($client->getStore(), $quality);
  233.         }
  234.         $configRepository $this->em->getRepository(Config::class);
  235.         return $configRepository->findOneByName(Config::IMG_PATH_NC)->getValue();
  236.     }
  237.     // TODO
  238.     // Check why this method is not in AttachmentTools
  239.     public function getLogoPathForEquipment(Equipment $equipment$quality 0)
  240.     {
  241.         $image null;
  242.         $mainImageId $equipment->getMainImageId();
  243.         foreach ($equipment->getAttachments() as $att)
  244.         {
  245.             // Get main Image if it's defined
  246.             if ($mainImageId !== null)
  247.             {
  248.                 if ($att->isImage() && $att->getId() == $mainImageId)
  249.                 {
  250.                     $image $att;
  251.                     break;
  252.                 }
  253.             }
  254.             else
  255.             {
  256.                 if ($att->isImage())
  257.                 {
  258.                     $image $att;
  259.                     break;
  260.                 }
  261.             }
  262.         }
  263.         if ($image !== null)
  264.         {
  265.             $url $this->router->generate('icod_platform_attachment_view', array(
  266.                 'id'         =>     $att->getId(),
  267.                 'quality'    =>    $quality,
  268.             ));
  269.             return $url;
  270.         }
  271.         $logoPath $this->getDefaultCameraPathForQuality($quality);
  272.         return "/".$logoPath->getValue();
  273.     }
  274.     public function getLogoPathForMission(Mission $mission$quality 0)
  275.     {
  276.         $image null;
  277.         // Plan.io Task #3427
  278.         if ($this->security->isGranted('view_confidential_attachments_for_missions'))
  279.         {
  280.             $attachments $this->em->getRepository(Attachment::class)->findBy(array(
  281.                 'mission'        =>    $mission,
  282.             ), array(
  283.                 'creationDate'    =>    'DESC',
  284.             ));
  285.         }
  286.         else
  287.         {
  288.             $attachments $this->em->getRepository(Attachment::class)->findBy(array(
  289.                 'mission'        =>    $mission,
  290.                 'confidential'    =>    0,
  291.             ), array(
  292.                 'creationDate'    =>    'DESC',
  293.             ));
  294.         }
  295.         // Plan.io Task #4309
  296.         $mainImageId $mission->getMainImageId();
  297.         foreach ($attachments as $att)
  298.         {
  299.             // Get main Image if it's defined
  300.             if ($mainImageId !== null)
  301.             {
  302.                 if ($att->isImage() && $att->getId() == $mainImageId)
  303.                 {
  304.                     $image $att;
  305.                     break;
  306.                 }
  307.             }
  308.             else
  309.             {
  310.                 if ($att->isImage())
  311.                 {
  312.                     $image $att;
  313.                     break;
  314.                 }
  315.             }
  316.         }
  317.         if ($image !== null)
  318.         {
  319.             $url $this->router->generate('icod_platform_attachment_view', array(
  320.                 'id'         =>     $att->getId(),
  321.                 'quality'    =>    $quality,
  322.             ));
  323.             return $url;
  324.         }
  325.         $logoPath $this->getDefaultCameraPathForQuality($quality);
  326.         return "/".$logoPath->getValue();
  327.     }
  328.     public function getLogoPathForArticle(Article $article$quality 0)
  329.     {
  330.         $image $article->getThumbnail();
  331.         if ($image !== null)
  332.         {
  333.             $url $this->router->generate('icod_platform_attachment_view', array(
  334.                 'id'         =>     $image->getId(),
  335.                 'quality'    =>    $quality,
  336.             ));
  337.             return $url;
  338.         }
  339.         $logoPath $this->getDefaultCameraPathForQuality($quality);
  340.         return "/".$logoPath->getValue();
  341.     }
  342.     public function getLogoPathForProduct(Product $product$quality 0)
  343.     {
  344.         if ($product->getLogo() !== null)
  345.             return $product->getLogo()->getUrlForDisplay($quality);
  346.         $logoPath $this->getDefaultCameraPathForQuality($quality);
  347.         return $logoPath->getValue();
  348.     }
  349.     public function getProfilePathForIndividual(Individual $outputdividual$quality 0)
  350.     {
  351.         $configRepository $this->em->getRepository(Config::class);
  352.         $logoPath null;
  353.         if ($outputdividual->getTitle() !== null)
  354.         {
  355.             if ($outputdividual->getTitle()->isSir())
  356.                 $logoPath $configRepository->findOneByName(Config::IMG_PATH_M);
  357.             else
  358.                 if ($outputdividual->getTitle()->isMadam())
  359.                     $logoPath $configRepository->findOneByName(Config::IMG_PATH_F);
  360.         }
  361.         if ($logoPath === null)
  362.         {
  363.             $logoPath $configRepository->findOneByName(Config::IMG_PATH_NC);
  364.         }
  365.         return $logoPath->getValue();
  366.     }
  367.     public function getAllProfilePath()
  368.     {
  369.         $configRepository $this->em->getRepository(Config::class);
  370.         $imgPathMConfig $configRepository->findOneByName(Config::IMG_PATH_M);
  371.         $imgPathFConfig $configRepository->findOneByName(Config::IMG_PATH_F);
  372.         $imgPathNCConfig $configRepository->findOneByName(Config::IMG_PATH_NC);
  373.         return array(
  374.             'img_path_m'     => $imgPathMConfig     !== null $imgPathMConfig->getValue()     : '',
  375.             'img_path_f'     => $imgPathFConfig     !== null $imgPathFConfig->getValue()     : '',
  376.             'img_path_nc'     => $imgPathNCConfig !== null $imgPathNCConfig->getValue() : '',
  377.         );
  378.     }
  379.     protected function getDefaultPathForHumanResource($quality)
  380.     {
  381.         $configRepository $this->em->getRepository(Config::class);
  382.         switch($quality)
  383.         {
  384.             case 480:
  385.             {
  386.                 $logoPath $configRepository->findOneByName(Config::IMG_PATH_M_480);
  387.                 break;
  388.             }
  389.             case 128:
  390.             {
  391.                 $logoPath $configRepository->findOneByName(Config::IMG_PATH_M_128);
  392.                 break;
  393.             }
  394.             case 80:
  395.             {
  396.                 $logoPath $configRepository->findOneByName(Config::IMG_PATH_M_80);
  397.                 break;
  398.             }
  399.             case 64:
  400.             {
  401.                 $logoPath $configRepository->findOneByName(Config::IMG_PATH_M_64);
  402.                 break;
  403.             }
  404.             default:
  405.             {
  406.                 $logoPath $configRepository->findOneByName(Config::IMG_PATH_M_480);
  407.                 break;
  408.             }
  409.         }
  410.         return $logoPath;
  411.     }
  412.     protected function getDefaultCameraPathForQuality($quality)
  413.     {
  414.         $configRepository $this->em->getRepository(Config::class);
  415.         switch($quality)
  416.         {
  417.             case 1024:
  418.             {
  419.                 $logoPath $configRepository->findOneByName(Config::IMG_PATH_CAMERA_1024);
  420.                 break;
  421.             }
  422.             case 512:
  423.             {
  424.                 $logoPath $configRepository->findOneByName(Config::IMG_PATH_CAMERA_512);
  425.                 break;
  426.             }
  427.             case 256:
  428.             {
  429.                 $logoPath $configRepository->findOneByName(Config::IMG_PATH_CAMERA_256);
  430.                 break;
  431.             }
  432.             case 128:
  433.             {
  434.                 $logoPath $configRepository->findOneByName(Config::IMG_PATH_CAMERA_128);
  435.                 break;
  436.             }
  437.             case 80:
  438.             {
  439.                 $logoPath $configRepository->findOneByName(Config::IMG_PATH_CAMERA_80);
  440.                 break;
  441.             }
  442.             case 64:
  443.             {
  444.                 $logoPath $configRepository->findOneByName(Config::IMG_PATH_CAMERA_64);
  445.                 break;
  446.             }
  447.             default:
  448.             {
  449.                 $logoPath $configRepository->findOneByName(Config::IMG_PATH_CAMERA);
  450.                 break;
  451.             }
  452.         }
  453.         return $logoPath;
  454.     }
  455.     public function handleProductLogo($product)
  456.     {
  457.         // Craft the file name
  458.         $imageName "product_".$product->getId();
  459.         // Get extension
  460.         $extension $product->getTempLogoExtension();
  461.         if ($extension != 'png' && $extension != 'jpg')
  462.         {
  463.             return null;
  464.         }
  465.         // Create a Image object
  466.         $image = new Image();
  467.         // Set it as a direct upload to bypass doctrine events
  468.         $image->setDirectUpload(1);
  469.         // Set the SocietyGroup, so we can get the correct path
  470.         $image->setSocietyGroup($product->getSocietyGroup());
  471.         // This renames the file using the timestamp
  472.         $image->setName($imageName);
  473.         $image->setExtension($extension);
  474.         // We need to flush the image in order to have its id
  475.         $this->em->persist($image);
  476.         try
  477.         {
  478.             $this->em->flush();
  479.         }
  480.         catch (\Exception $e)
  481.         {
  482.             $this->logTools->errorLog($e->getMessage());
  483.             return null;
  484.         }
  485.         // Get the correct file name with its destination
  486.         $finalImage $image->getPhpPath();
  487.         // Now get the image from the JS
  488.         $imageData $product->getTempLogoBase64();
  489.         $imageData base64_decode($imageData);
  490.         if ($imageData === false)
  491.         {
  492.             return null;
  493.         }
  494.         $source imagecreatefromstring($imageData);
  495.         if ($source === false)
  496.         {
  497.             return null;
  498.         }
  499.         $localion $image->getPhpPathOnly();
  500.         if (!file_exists($localion))
  501.         {
  502.             if (!mkdir($localion0755true))
  503.             {
  504.                 return null;
  505.             }
  506.         }
  507.         if ($extension == 'jpg')
  508.             $imageSave imagejpeg($source$finalImage100);
  509.         else
  510.         {
  511.             imagealphablending($sourcefalse);
  512.             imagesavealpha($sourcetrue);
  513.             $imageSave imagepng($source$finalImage);
  514.         }
  515.         if ($imageSave === false)
  516.         {
  517.             return null;
  518.         }
  519.         imagedestroy($source);
  520.         // Make smaller versions
  521.         $original $finalImage;
  522.         list($width$height) = getimagesize($original);
  523.         if ($extension == 'jpg')
  524.             $exif = @exif_read_data($original);
  525.         else
  526.             $exif null;
  527.         if ($exif !== null && !empty($exif) && array_key_exists('Orientation'$exif))
  528.             $ort $exif['Orientation'];
  529.         else
  530.             $ort null;
  531.         $name128 $image->getPhpPathOnly().'/'.$image->getId().'_128.'.$extension;
  532.         $name256 $image->getPhpPathOnly().'/'.$image->getId().'_256.'.$extension;
  533.         $name512 $image->getPhpPathOnly().'/'.$image->getId().'_512.'.$extension;
  534.         $name1024 $image->getPhpPathOnly().'/'.$image->getId().'_1024.'.$extension;
  535.         $this->smart_resize_image$originalnull1280true$name128falsefalse75false$ort);
  536.         $this->smart_resize_image$originalnull2560true$name256falsefalse75false$ort);
  537.         $this->smart_resize_image$originalnull5120true$name512falsefalse75false$ort);
  538.         $this->smart_resize_image$originalnull10240true$name1024falsefalse75false$ort);
  539.         // Attach the image to the main object
  540.         $product->setLogo($image);
  541.         $this->em->persist($product);
  542.         try
  543.         {
  544.             $this->em->flush();
  545.         }
  546.         catch (\Exception $e)
  547.         {
  548.             $this->logTools->errorLog($e->getMessage());
  549.             return null;
  550.         }
  551.         return $image;
  552.     }
  553.     public function hasExifData($extension)
  554.     {
  555.         $ext_whitelist = array('jpg''jpeg''tiff''tif');
  556.         $extension strtolower($this->extension);
  557.         if (in_array($extension$ext_whitelist))
  558.         {
  559.             return true;
  560.         }
  561.         else
  562.         {
  563.             return false;
  564.         }
  565.     }
  566.     public function handleOrientation($filePath)
  567.     {
  568.         if(exif_imagetype($filePath) == IMAGETYPE_JPEG)
  569.         {
  570.             try
  571.             {
  572.                 $exif exif_read_data($filePath);
  573.             }
  574.             catch (\Exception $exp)
  575.             {
  576.                 $exif false;
  577.             }
  578.             if ($exif)
  579.             {
  580.                 if (!empty($exif) && array_key_exists('Orientation'$exif) && !empty($exif['Orientation']))
  581.                 {
  582.                     $imageResource imagecreatefromjpeg($filePath); // provided that the image is jpeg. Use relevant function otherwise
  583.                     switch ($exif['Orientation'])
  584.                     {
  585.                         case 3:
  586.                         {
  587.                             $image imagerotate($imageResource1800);
  588.                             break;
  589.                         }
  590.                         case 6:
  591.                         {
  592.                             $image imagerotate($imageResource, -900);
  593.                             break;
  594.                         }
  595.                         case 8:
  596.                         {
  597.                             $image imagerotate($imageResource900);
  598.                             break;
  599.                         }
  600.                         default:
  601.                         {
  602.                             $image $imageResource;
  603.                             break;
  604.                         }
  605.                     }
  606.                 }
  607.             }
  608.             else
  609.             {
  610.                 $image imagecreatefromjpeg($filePath);
  611.             }
  612.             return $image;
  613.         }
  614.     }
  615.     // https://github.com/Nimrod007/PHP_image_resize
  616.     /**
  617.      * easy image resize function
  618.      * @param  $file - file name to resize
  619.      * @param  $string - The image data, as a string
  620.      * @param  $width - new image width
  621.      * @param  $height - new image height
  622.      * @param  $proportional - keep image proportional, default is no
  623.      * @param  $output - name of the new file (include path if needed)
  624.      * @param  $delete_original - if true the original image will be deleted
  625.      * @param  $use_linux_commands - if set to true will use "rm" to delete the image, if false will use PHP unlink
  626.      * @param  $quality - enter 1-100 (100 is best quality) default is 100
  627.      * @param  $grayscale - if true, image will be grayscale (default is false)
  628.      * @return boolean|resource
  629.      */
  630.     public function smart_resize_image(
  631.         $file,
  632.         $string             null,
  633.         $width              0,
  634.         $height             0,
  635.         $proportional       false,
  636.         $output             'file',
  637.         $delete_original    true,
  638.         $use_linux_commands false,
  639.         $quality            100,
  640.         $grayscale          false,
  641.         $ort                  null
  642.     )
  643.     {
  644.         if ( $height <= && $width <= ) return false;
  645.         if ( $file === null && $string === null ) return false;
  646.         // Setting defaults and meta
  647.         $outputfo                         $file !== null getimagesize($file) : getimagesizefromstring($string);
  648.         $image                        '';
  649.         $final_width                  0;
  650.         $final_height                 0;
  651.         list($width_old$height_old) = $outputfo;
  652.         $cropHeight $cropWidth 0;
  653.         // Calculating proportionality
  654.         if ($proportional)
  655.         {
  656.             if      ($width  == 0)  $factor $height/$height_old;
  657.             elseif  ($height == 0)  $factor $width/$width_old;
  658.                 else                    $factor min$width $width_old$height $height_old );
  659.             $final_width  round$width_old $factor );
  660.             $final_height round$height_old $factor );
  661.         }
  662.         else
  663.         {
  664.             $final_width = ( $width <= ) ? $width_old $width;
  665.             $final_height = ( $height <= ) ? $height_old $height;
  666.             $widthX $width_old $width;
  667.             $heightX $height_old $height;
  668.             $x min($widthX$heightX);
  669.             $cropWidth = ($width_old $width $x) / 2;
  670.             $cropHeight = ($height_old $height $x) / 2;
  671.         }
  672.         // Loading image to memory according to type
  673.         switch ( $outputfo[2] )
  674.         {
  675.             case IMAGETYPE_JPEG:  $file !== null $image imagecreatefromjpeg($file) : $image imagecreatefromstring($string);  break;
  676.             case IMAGETYPE_GIF:   $file !== null $image imagecreatefromgif($file)  : $image imagecreatefromstring($string);  break;
  677.             case IMAGETYPE_PNG:   $file !== null $image imagecreatefrompng($file)  : $image imagecreatefromstring($string);  break;
  678.             default: return false;
  679.         }
  680.         // Making the image grayscale, if needed
  681.         if ($grayscale)
  682.         {
  683.             imagefilter($imageIMG_FILTER_GRAYSCALE);
  684.         }
  685.         // This is the resizing/resampling/transparency-preserving magic
  686.         $image_resized imagecreatetruecolor$final_width$final_height );
  687.         if ( ($outputfo[2] == IMAGETYPE_GIF) || ($outputfo[2] == IMAGETYPE_PNG) )
  688.         {
  689.             $transparency imagecolortransparent($image);
  690.             $palletsize imagecolorstotal($image);
  691.             if ($transparency >= && $transparency $palletsize)
  692.             {
  693.                 $transparent_color  imagecolorsforindex($image$transparency);
  694.                 $transparency       imagecolorallocate($image_resized$transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
  695.                 imagefill($image_resized00$transparency);
  696.                 imagecolortransparent($image_resized$transparency);
  697.             }
  698.             elseif ($outputfo[2] == IMAGETYPE_PNG)
  699.             {
  700.                 imagealphablending($image_resizedfalse);
  701.                 $color imagecolorallocatealpha($image_resized000127);
  702.                 imagefill($image_resized00$color);
  703.                 imagesavealpha($image_resizedtrue);
  704.             }
  705.         }
  706.         imagecopyresampled($image_resized$image00$cropWidth$cropHeight$final_width$final_height$width_old $cropWidth$height_old $cropHeight);
  707.         // Reapply original Orientation
  708.         if (!empty($ort))
  709.         {
  710.             switch ($ort)
  711.             {
  712.                 case 3:
  713.                     $image_resized imagerotate($image_resized1800);
  714.                     break;
  715.                 case 6:
  716.                     $image_resized imagerotate($image_resized, -900);
  717.                     break;
  718.                 case 8:
  719.                     $image_resized imagerotate($image_resized900);
  720.                     break;
  721.             }
  722.         }
  723.         // Taking care of original, if needed
  724.         if ( $delete_original )
  725.         {
  726.             @unlink($file);
  727.         }
  728.         // Preparing a method of providing result
  729.         switch ( strtolower($output) )
  730.         {
  731.             case 'browser':
  732.                 $mime image_type_to_mime_type($outputfo[2]);
  733.                 header("Content-type: $mime");
  734.                 $output null;
  735.             break;
  736.             case 'file':
  737.                 $output $file;
  738.                 break;
  739.             case 'return':
  740.                 return $image_resized;
  741.                 break;
  742.             default:
  743.             break;
  744.         }
  745.         // Writing image according to type to the output destination and image quality
  746.         switch ( $outputfo[2] )
  747.         {
  748.             case IMAGETYPE_GIF:   imagegif($image_resized$output);    break;
  749.             case IMAGETYPE_JPEG:  imagejpeg($image_resized$output$quality);   break;
  750.             case IMAGETYPE_PNG:
  751.             $quality - (int)((0.9*$quality)/10.0);
  752.             imagepng($image_resized$output$quality);
  753.             break;
  754.             default: return false;
  755.         }
  756.         return true;
  757.       }
  758. }