1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <?php
- namespace App\Handlers;
- class CompressImageHandler
- {
- private $image;
- private $imageinfo;
- private $percent = 0.5;
-
- public function Upload()
- {
- $file = $_FILES['img'];
-
- $filePath = $file['tmp_name'];
-
- $this->_openImage($filePath);
-
- ob_start();
- $fileName = $file['name'];
- $ext = pathinfo($fileName, PATHINFO_EXTENSION);
- if ($ext == 'jpg' || $ext == 'jpeg') {
- imagejpeg($this->image);
- }
- if ($ext == 'png') {
- imagepng($this->image);
- }
- $contents = ob_get_contents();
- ob_end_clean();
- imagedestroy($this->image);
- return $contents;
- }
-
- private function _openImage($src)
- {
- list($width, $height, $type, $attr) = getimagesize($src);
- $this->imageinfo = array(
- 'width' => $width,
- 'height' => $height,
- 'type' => image_type_to_extension($type, false),
- 'attr' => $attr
- );
- $fun = "imagecreatefrom" . $this->imageinfo['type'];
- $this->image = $fun($src);
- $this->_thumpImage();
- }
-
- private function _thumpImage()
- {
- $new_width = $this->imageinfo['width'] * $this->percent;
- $new_height = $this->imageinfo['height'] * $this->percent;
- $image_thump = imagecreatetruecolor($new_width, $new_height);
-
- imagesavealpha($image_thump, true);
- $black = imagecolorallocate($image_thump, 0, 0, 0);
- imagefilledrectangle($image_thump, 0, 0, 150, 25, $black);
- $trans_colour = imagecolorallocatealpha($image_thump, 0, 0, 0, 127);
- imagefill($image_thump, 0, 0, $trans_colour);
-
- imagecopyresampled($image_thump, $this->image, 0, 0, 0, 0, $new_width, $new_height, $this->imageinfo['width'], $this->imageinfo['height']);
- imagedestroy($this->image);
- $this->image = $image_thump;
- }
- }
|