Last active
February 21, 2024 03:54
-
-
Save tranchausky/fc831aa1d1c438c9aa278d8a914af25e to your computer and use it in GitHub Desktop.
php resize image (laravel -plupload)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Services; | |
use Illuminate\Filesystem\Filesystem; | |
class FileUploadChurkService extends BaseService | |
{ | |
public function __construct() | |
{ | |
} | |
public function moveFileCompleted($from = '', $pathNew = '', $replaceFrom = '', $replaceTo = '', $isImageCompress = false, $isThumb = false, $sizeThump = 400) { | |
if (!file_exists($pathNew)) { | |
$file = new Filesystem(); | |
$file->makeDirectory($pathNew, 755, true, true); | |
} | |
if(file_exists($from)){ | |
$newPath = str_replace($replaceFrom, $replaceTo, $from); | |
if($isImageCompress == true){ | |
$this->compressImage($from, $newPath, 60); | |
}else{ | |
rename($from, $newPath); | |
} | |
if(file_exists($newPath)){ | |
if(file_exists($from)){ | |
unlink($from); | |
} | |
} | |
if($isThumb == true && $this->isImageFile($newPath)){ | |
$toResize = $this->getThumbLinkImage($newPath); | |
$this->resizeImage($newPath, $toResize, $sizeThump); | |
} | |
return $newPath; | |
}else{ | |
return $from; | |
} | |
} | |
//default rename folder before last folder | |
public static function getThumbLinkImage($url = '') | |
{ | |
$dir = dirname($url); | |
$file = basename($url); | |
// Split the directory path by "/" | |
$pathParts = explode('/', trim($dir, '/')); | |
// Get the last folder | |
$lastFolder = array_pop($pathParts); | |
// Prefix the last folder | |
$newFolder = $lastFolder.'_thumb'; | |
// Reassemble the directory path | |
$newDir = implode('/', $pathParts) . '/' . $newFolder; | |
// Reassemble the new URL | |
$newUrl = $newDir . '/' . $file; | |
if (!file_exists($newDir)) { | |
$file = new Filesystem(); | |
$file->makeDirectory($newDir, 755, true, true); | |
} | |
return $newUrl; | |
} | |
private function isImageFile($url = '') | |
{ | |
$imgExts = array("jpg", "jpeg", "png"); | |
$url ='path/to/image.png'; | |
$urlExt = pathinfo($url, PATHINFO_EXTENSION); | |
if (in_array($urlExt, $imgExts)) { | |
return true; | |
} | |
return false; | |
} | |
private function resizeImage($from = '', $toResize = '', $after_width = 400){ | |
$file = new Filesystem(); | |
$file->copy($from, $toResize); | |
$source_url_parts = pathinfo($toResize); | |
$filename = $source_url_parts['filename']; | |
$extension = $source_url_parts['extension']; | |
$extension = strtolower($extension); | |
//define the quality from 1 to 100 | |
$quality = 60; | |
//detect the width and the height of original image | |
list($width, $height) = getimagesize($toResize); | |
// $width; | |
// $height; | |
//resize only when the original image is larger than expected with. | |
//this helps you to avoid from unwanted resizing. | |
if ($width > $after_width) { | |
//get the reduced width | |
$reduced_width = ($width - $after_width); | |
//now convert the reduced width to a percentage and round it to 2 decimal places | |
$reduced_radio = round(($reduced_width / $width) * 100, 2); | |
//ALL GOOD! let's reduce the same percentage from the height and round it to 2 decimal places | |
$reduced_height = round(($height / 100) * $reduced_radio, 2); | |
//reduce the calculated height from the original height | |
$after_height = $height - $reduced_height; | |
//Now detect the file extension | |
//if the file extension is 'jpg', 'jpeg', 'JPG' or 'JPEG' | |
if ($extension == 'jpg' || $extension == 'jpeg') { | |
//then return the image as a jpeg image for the next step | |
$img = imagecreatefromjpeg($toResize); | |
} elseif ($extension == 'png') { | |
//then return the image as a png image for the next step | |
$img = imagecreatefrompng($toResize); | |
} else { | |
//show an error message if the file extension is not available | |
//echo 'image extension is not supporting'; | |
} | |
//HERE YOU GO :) | |
//Let's do the resize thing | |
//imagescale([returned image], [width of the resized image], [height of the resized image], [quality of the resized image]); | |
// $imgResized = imagescale($img, $after_width, $after_height, $quality); | |
$out = imagecreatetruecolor($after_width, $after_height); | |
imagecopyresampled($out, $img, 0, 0, 0, 0, $after_width, $after_height, $width, $height); | |
//output image | |
imagepng($out, $toResize); | |
// if($imgResized != false){ | |
// //now save the resized image with a suffix called "-resized" and with its extension. | |
// //imagejpeg($imgResized, $filename . '-resized.'.$extension); | |
// imagejpeg($imgResized, $to); | |
// //Finally frees any memory associated with image | |
// //**NOTE THAT THIS WONT DELETE THE IMAGE | |
// imagedestroy($img); | |
// imagedestroy($imgResized); | |
// } | |
$this->compressImage($toResize, $toResize, 90); | |
} | |
} | |
private function compressImage($src, $dest , $quality = 60) | |
{ | |
$info = getimagesize($src); | |
if ($info['mime'] == 'image/jpeg') | |
{ | |
$image = imagecreatefromjpeg($src); | |
} | |
elseif ($info['mime'] == 'image/gif') | |
{ | |
$image = imagecreatefromgif($src); | |
} | |
elseif ($info['mime'] == 'image/png') | |
{ | |
$image = imagecreatefrompng($src); | |
} | |
else | |
{ | |
//die('Unknown image file format'); | |
rename($src, $dest); | |
return $dest; | |
} | |
imagejpeg($image, $dest, $quality); | |
return $dest; | |
} | |
/** | |
* save file service | |
* $targetDir after public/ | |
*/ | |
public function saveFileSV($targetDir ='') | |
{ | |
// Make sure file is not cached (as it happens for example on iOS devices) | |
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); | |
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); | |
header("Cache-Control: no-store, no-cache, must-revalidate"); | |
header("Cache-Control: post-check=0, pre-check=0", false); | |
header("Pragma: no-cache"); | |
// 1 minutes execution time | |
@set_time_limit(1 * 60); | |
// Uncomment this one to fake upload time | |
// usleep(5000); | |
// Settings | |
$cleanupTargetDir = true; // Remove old files | |
$maxFileAge = 5 * 3600; // Temp file age in seconds | |
// Create target dir | |
if (!file_exists($targetDir)) { | |
$file = new Filesystem(); | |
$file->makeDirectory($targetDir, 755, true, true); | |
} | |
// Get a file name | |
if (isset($_REQUEST["name"])) { | |
$fileName = $_REQUEST["name"]; | |
} elseif (!empty($_FILES)) { | |
$fileName = $_FILES["file"]["name"]; | |
} else { | |
$fileName = uniqid("file_"); | |
} | |
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName; | |
// Chunking might be enabled | |
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0; | |
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0; | |
// Remove old temp files | |
if ($cleanupTargetDir) { | |
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) { | |
return response()->json([ | |
"jsonrpc" => "2.0", | |
"id" => "id", | |
"error" => [ | |
"code" => 100, | |
"message" => "Failed to open temp directory.", | |
] | |
]); | |
} | |
while (($file = readdir($dir)) !== false) { | |
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file; | |
// If temp file is current file proceed to the next | |
if ($tmpfilePath == "{$filePath}.part") { | |
continue; | |
} | |
// Remove temp file if it is older than the max age and is not the current file | |
if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) { | |
@unlink($tmpfilePath); | |
} | |
} | |
closedir($dir); | |
} | |
// Open temp file | |
if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) { | |
return response()->json([ | |
"jsonrpc" => "2.0", | |
"id" => "id", | |
"error" => [ | |
"code" => 102, | |
"message" => "Failed to open output stream.", | |
] | |
]); | |
} | |
if (!empty($_FILES)) { | |
if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) { | |
return response()->json([ | |
"jsonrpc" => "2.0", | |
"id" => "id", | |
"error" => [ | |
"code" => 103, | |
"message" => "Failed to move uploaded file.", | |
] | |
]); | |
} | |
// Read binary input stream and append it to temp file | |
if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) { | |
return response()->json([ | |
"jsonrpc" => "2.0", | |
"id" => "id", | |
"error" => [ | |
"code" => 101, | |
"message" => "Failed to open input stream.", | |
] | |
]); | |
} | |
} else { | |
if (!$in = @fopen("php://input", "rb")) { | |
return response()->json([ | |
"jsonrpc" => "2.0", | |
"id" => "id", | |
"error" => [ | |
"code" => 101, | |
"message" => "Failed to open input stream.", | |
] | |
]); | |
} | |
} | |
while ($buff = fread($in, 4096)) { | |
fwrite($out, $buff); | |
} | |
@fclose($out); | |
@fclose($in); | |
// Check if file has been uploaded | |
if (!$chunks || $chunk == $chunks - 1) { | |
rename("{$filePath}.part", $filePath); | |
} | |
// Return Success JSON-RPC response | |
return response()->json([ | |
'filepath' => base64_encode($filePath), | |
"jsonrpc" => "2.0", | |
"result" => null, | |
"id" => "id", | |
]); | |
} | |
public function removeFile($path = ''){ | |
if(file_exists($path)){ | |
unlink($path); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Services; | |
use Illuminate\Filesystem\Filesystem; | |
use Intervention\Image\Facades\Image; | |
class FileUploadChurkService extends BaseService | |
{ | |
public function __construct() | |
{ | |
} | |
public function moveFileCompleted($from = '', $pathNew = '', $replaceFrom = '', $replaceTo = '', $isImageCompress = false, $isThumb = false, $sizeThump = 400) { | |
if (!file_exists($pathNew)) { | |
$file = new Filesystem(); | |
$file->makeDirectory($pathNew, 755, true, true); | |
} | |
if(file_exists($from)){ | |
$newPath = str_replace($replaceFrom, $replaceTo, $from); | |
if($isImageCompress == true){ | |
$this->compressImage($from, $newPath, 60); | |
}else{ | |
rename($from, $newPath); | |
} | |
if(file_exists($newPath)){ | |
if(file_exists($from)){ | |
unlink($from); | |
} | |
} | |
if($isThumb == true && $this->isImageFile($newPath)){ | |
$toResize = $this->getThumbLinkImage($newPath); | |
$this->resizeImage($newPath, $toResize, $sizeThump); | |
} | |
return $newPath; | |
}else{ | |
return $from; | |
} | |
} | |
/** | |
* default rename last folder add prefix _thumb | |
*/ | |
public static function getThumbLinkImage($url = '') | |
{ | |
$dir = dirname($url); | |
$file = basename($url); | |
$pathParts = explode('/', trim($dir, '/')); | |
$lastFolder = array_pop($pathParts); | |
$newFolder = $lastFolder.'_thumb'; | |
$newDir = implode('/', $pathParts) . '/' . $newFolder; | |
$newUrl = $newDir . '/' . $file; | |
$filePath = parse_url($newUrl, PHP_URL_PATH); | |
$newUrl = substr_replace($filePath, 'webp', strrpos($filePath, '.') + 1); //rename file to wepb | |
if (!file_exists($newDir)) { | |
$file = new Filesystem(); | |
$file->makeDirectory($newDir, 755, true, true); | |
} | |
return $newUrl; | |
} | |
private function isImageFile($url = '') | |
{ | |
$imgExts = array("jpg", "jpeg", "png"); | |
$url ='path/to/image.png'; | |
$urlExt = pathinfo($url, PATHINFO_EXTENSION); | |
if (in_array($urlExt, $imgExts)) { | |
return true; | |
} | |
return false; | |
} | |
private function resizeImage($from = '', $toResize = '', $after_width = 400) | |
{ | |
list($width, $height) = getimagesize($from); | |
if ($width > $after_width) { | |
$reduced_width = ($width - $after_width); | |
$reduced_radio = round(($reduced_width / $width) * 100, 2); | |
$reduced_height = round(($height / 100) * $reduced_radio, 2); | |
$after_height = $height - $reduced_height; | |
$thumb = Image::make($from); | |
$thumb->resize($after_width, $after_height, function ($constraint) { | |
$constraint->aspectRatio(); | |
}); | |
$thumb->stream('webp'); | |
$thumb->save($toResize); | |
return $toResize; | |
}else{ | |
$file = new Filesystem(); | |
$file->copy($from, $toResize); | |
} | |
} | |
private function compressImage($src, $dest , $quality = 60) | |
{ | |
$info = getimagesize($src); | |
if ($info['mime'] == 'image/jpeg') | |
{ | |
$image = imagecreatefromjpeg($src); | |
} | |
elseif ($info['mime'] == 'image/gif') | |
{ | |
$image = imagecreatefromgif($src); | |
} | |
elseif ($info['mime'] == 'image/png') | |
{ | |
$image = imagecreatefrompng($src); | |
} | |
else | |
{ | |
//die('Unknown image file format'); | |
rename($src, $dest); | |
return $dest; | |
} | |
imagejpeg($image, $dest, $quality); | |
return $dest; | |
} | |
/** | |
* save file service | |
* $targetDir after public/ | |
*/ | |
public function saveFileSV($targetDir ='') | |
{ | |
// Make sure file is not cached (as it happens for example on iOS devices) | |
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); | |
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); | |
header("Cache-Control: no-store, no-cache, must-revalidate"); | |
header("Cache-Control: post-check=0, pre-check=0", false); | |
header("Pragma: no-cache"); | |
// 1 minutes execution time | |
@set_time_limit(1 * 60); | |
// Uncomment this one to fake upload time | |
// usleep(5000); | |
// Settings | |
$cleanupTargetDir = true; // Remove old files | |
$maxFileAge = 5 * 3600; // Temp file age in seconds | |
// Create target dir | |
if (!file_exists($targetDir)) { | |
$file = new Filesystem(); | |
$file->makeDirectory($targetDir, 755, true, true); | |
} | |
// Get a file name | |
if (isset($_REQUEST["name"])) { | |
$fileName = $_REQUEST["name"]; | |
} elseif (!empty($_FILES)) { | |
$fileName = $_FILES["file"]["name"]; | |
} else { | |
$fileName = uniqid("file_"); | |
} | |
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName; | |
// Chunking might be enabled | |
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0; | |
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0; | |
// Remove old temp files | |
if ($cleanupTargetDir) { | |
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) { | |
return response()->json([ | |
"jsonrpc" => "2.0", | |
"id" => "id", | |
"error" => [ | |
"code" => 100, | |
"message" => "Failed to open temp directory.", | |
] | |
]); | |
} | |
while (($file = readdir($dir)) !== false) { | |
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file; | |
// If temp file is current file proceed to the next | |
if ($tmpfilePath == "{$filePath}.part") { | |
continue; | |
} | |
// Remove temp file if it is older than the max age and is not the current file | |
if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) { | |
@unlink($tmpfilePath); | |
} | |
} | |
closedir($dir); | |
} | |
// Open temp file | |
if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) { | |
return response()->json([ | |
"jsonrpc" => "2.0", | |
"id" => "id", | |
"error" => [ | |
"code" => 102, | |
"message" => "Failed to open output stream.", | |
] | |
]); | |
} | |
if (!empty($_FILES)) { | |
if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) { | |
return response()->json([ | |
"jsonrpc" => "2.0", | |
"id" => "id", | |
"error" => [ | |
"code" => 103, | |
"message" => "Failed to move uploaded file.", | |
] | |
]); | |
} | |
// Read binary input stream and append it to temp file | |
if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) { | |
return response()->json([ | |
"jsonrpc" => "2.0", | |
"id" => "id", | |
"error" => [ | |
"code" => 101, | |
"message" => "Failed to open input stream.", | |
] | |
]); | |
} | |
} else { | |
if (!$in = @fopen("php://input", "rb")) { | |
return response()->json([ | |
"jsonrpc" => "2.0", | |
"id" => "id", | |
"error" => [ | |
"code" => 101, | |
"message" => "Failed to open input stream.", | |
] | |
]); | |
} | |
} | |
while ($buff = fread($in, 4096)) { | |
fwrite($out, $buff); | |
} | |
@fclose($out); | |
@fclose($in); | |
// Check if file has been uploaded | |
if (!$chunks || $chunk == $chunks - 1) { | |
rename("{$filePath}.part", $filePath); | |
} | |
// Return Success JSON-RPC response | |
return response()->json([ | |
'filepath' => base64_encode($filePath), | |
"jsonrpc" => "2.0", | |
"result" => null, | |
"id" => "id", | |
]); | |
} | |
public function removeFile($path = ''){ | |
if(file_exists($path)){ | |
unlink($path); | |
} | |
$thumb = $this->getThumbLinkImage($path); | |
if(file_exists($thumb)){ | |
unlink($thumb); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment