Skip to content

Instantly share code, notes, and snippets.

@irkreja
Created November 10, 2018 19:39
Show Gist options
  • Save irkreja/5bb6f97e5e24dca68da92efcb78ccba2 to your computer and use it in GitHub Desktop.
Save irkreja/5bb6f97e5e24dca68da92efcb78ccba2 to your computer and use it in GitHub Desktop.
Save and Optimize Image in PHP
<?php
// include composer autoload
require 'vendor/autoload.php';
// import the Intervention Image Manager Class
use Intervention\Image\ImageManager;
if (!function_exists('optimizeImage')) {
/**
* Save and Optimize Image
*/
function optimizeImage($file, $fileName, $path, $width = null, $height = null)
{
// create an image manager instance with favored driver
$manager = new ImageManager(array('driver' => 'gd'));
$fileNameWithExtension = $file['name'];
$ModifiedFileNameWithoutExtension = str_slug($fileName, '_') . '_' . md5(microtime());
$fileExtension = pathinfo($fileNameWithExtension, PATHINFO_EXTENSION);
// $ModifiedFileNameWithExtension = $ModifiedFileNameWithoutExtension.'.'.$fileExtension;
$ModifiedFileNameWithExtension = $ModifiedFileNameWithoutExtension . '.' . 'jpg';
// to finally create image instances
$image = $manager->make($file['tmp_name']);
$save_path = dirname(__DIR__) . $path;
if (!file_exists($save_path)) {
mkdir($save_path, 0777, true);
}
$pathWithFileName = $save_path . $ModifiedFileNameWithExtension;
if (isset($width)) {
$image->resize($width, $height, function ($constraint) {
$constraint->aspectRatio();
})->insert('watermark.png', 'bottom-right', 10, 10)
->encode('jpg', 75)
->save($pathWithFileName);
} else {
$image->insert('watermark.png', 'bottom-right', 10, 10)
->encode('jpg', 75)
->save($pathWithFileName);
}
return $ModifiedFileNameWithExtension;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment