How to set Image Resolution in uploaded Image in Laravel Intervention - php

Please, anyone, help me I want to set the Image Resolution to 300dpi for the uploaded image using Image Intervention.
Any alternate solution is also welcome.
What I want:
Upload Image -> Resize image to (100 X 100) -> Set image size to less than 30KB -> and set image resolution to 300dpi -> auto download
I have done everything else the resolution to my project... Here I'm sending the code and link ...
$width = 400;
$height = 200;
$file = $request->file('upload');
$image = Image::make($file)->resize($width, $height)->encode('jpg');
$headers = [
'Content-Type' => 'image/jpeg',
'Content-Disposition' => 'attachment; filename=utipanpsa_'.$request->type.'.jpg',
];
return response()->stream(function() use ($image) {
echo $image;
}, 200, $headers);
https://www.utipanpsa.com/cropping-tools

acording to document you can use imageresolution() if you have php >= 7.2 like this:
//sets the image resolution to 200
imageresolution($imageRecource, 200);

Related

How to compress image before uploading in Laravel?

I'm making a images gallery website where users can upload any image and they will be displayed on frontend. I need to compress images without effecting it's quality to reduce there size so that page load speed should not effect that much. I'm using following code to upload image:
$rules = array('file' => 'required');
$destinationPath = 'assets/images/pages'
$validator = Validator::make(array('file' => $file), $rules);
if ($validator->passes()) {
$filename = time() . $uploadcount . '.' . $file->getClientOriginalExtension();
$file->move($destinationPath, $filename);
return $filename;
} else {
return '';
}
The best and easiest way to compress images before uploading to the server, I found here:-
https://github.com/spatie/laravel-image-optimizer
You need to optimize the image for web usage as user may upload images that are way to large (Either in size or resolution). You may also want to remove the meta data from the images to decrease the size even more. Intervention Image perfect for resizing/optimizing images for web usage in Laravel. You need to optimize the image before it is saved so that the optimized version is used when loading the web page.
Intervention Image
https://tinypng.com provides an API service for compressing images. All you need to do is install their PHP library in Laravel, get a developer key from their website. After that by the adding the below code, you can compress your uploaded image. In the code, I am assuming you have stored your file under 'storage' directory.
$filepath = public_path('storage/profile_images/'.$filename);
\Tinify\setKey("YOUR_API_KEY");
$source = \Tinify\fromFile($filepath);
$source->toFile($filepath);
Here is the link to a blog which explains how to upload and compress images in Laravel http://artisansweb.net/guide-upload-compress-images-laravel
**Using core php **
function compress($source_image, $compress_image)
{
$image_info = getimagesize($source_image);
if ($image_info['mime'] == 'image/jpeg') {
$source_image = imagecreatefromjpeg($source_image);
imagejpeg($source_image, $compress_image, 20); //for jpeg or gif, it should be 0-100
} elseif ($image_info['mime'] == 'image/png') {
$source_image = imagecreatefrompng($source_image);
imagepng($source_image, $compress_image, 3);
}
return $compress_image;
}
public function store(Request $request)
{
$image_name = $_FILES['image']['name'];
$tmp_name = $_FILES['image']['tmp_name'];
$directory_name = public_path('/upload/image/');
$file_name = $directory_name . $image_name;
move_uploaded_file($tmp_name, $file_name);
$compress_file = "compress_" . $image_name;
$compressed_img = $directory_name . $compress_file;
$compress_image = $this->compress($file_name, $compressed_img);
unlink($file_name);
}

Resizing an image with Intervention

Im trying to use Intervention with AWS S3, but the resize method is not working for me.
$img = Image::make($file)->rotate($rotate)->crop($width, $width, $x, $y);
$img->backup();
foreach(Config::get('img.image-sizes') as $_k => $_v){
$img->resize($_v['w'], $_v['h']);
$s3->queue($img, $name);
$img->reset();
}
The images upload fine to S3, but resize fails, I get all images the size of the original image
If I call save() on the image, the resize works, but I do not wish to save the image as I am uploading via S3, putting the $img as the body:
$this->commands[] = $this->s3->getCommand('PutObject', [
'Bucket' => env('AWS_BUCKET'),
'Key' => Config::get('img.image-path').$name,
'Body' => $img,
'ContentType' => $img->mime(),
'ACL' => 'public-read'
]);
To get this to work will I have to call save on each image first? If so is there a way to get this to play nice with S3, ideally I do not want to save them to my server first before sending them off to S3.
This is the code I used to get my uploaded images resized and saved to Amazon S3 using Laravel 5 and Intervention.
$imageFile = \Image::make($imageUpload)->resize(600, 600)->stream();
$imageFile = $imageFile->__toString();
$filename = 'myFileName.png';
$s3 = \Storage::disk('s3');
$s3_response = $s3->put('/'.$filename, $imageFile, 'public');

getimagesize() not working for image upload

My attempt at getting the size of a newly uploaded image appears not to be working properly.
list($w, $h) = getimagesize($_FILES['image_field']);
echo 'width:'.$w;
outputs:
width:
How is this possible? I know for a fact the image (.jpg) is uploading fine because it's now on my server.
Use this code:
list($w, $h) = getimagesize($_FILES["image_field"]["tmp_name"]);
first you need to upload file then pass the uploaded location
getimagesize("location_of_file/".$file_name);
OR
getimagesize($path['path'].'/'.$_POST['name']);
OR
$file_name=$_FILES['fileToUpload']['name'];
getimagesize($target_dir.'/'.$file_name);
OR
$file_tmp=$_FILES['fileToUpload']['tmp_name']; list($width, $height) =
getimagesize($file_tmp);
$file_width=$width;
$file_height=$height;

How to upload image to AWS S3 in PHP from memory?

So I currently have an upload system working using AWS S3 to upload images.
Here's the code:
//Upload image to S3
$s3 = Aws\S3\S3Client::factory(array('key' => /*mykey*/, 'secret' => /*myskey*/,));
try {
$s3->putObject(array(
'Bucket' => "bucketname",
'Key' => $file_name,
'Body' => fopen(/*filelocation*/, 'r+')
));
} catch(Exception $e) {
//Error
}
This image can be a jpeg or png, and I want to convert it to a png before uploading. To do this I use:
//This is simplified, please don't warn about transparency, etc.
$image = imagecreatetruecolor($width, $height);
imagecopyresampled($image, $source, 0, 0, 0, 0, etc.);
So I have this $image object in memory.
I want to upload this to S3 without having to save it locally, upload it and then delete it locally; this extra step seems pointless. But I can't work out how to upload this $image object directly.
Any ideas how this would be done? I'd assumed fopen() would create an object of a similar type to imagecreatetruecolor(), but I've tried passing the $image object in and it doesn't work - whereas it does if I open an image locally with fopen().
You can capture the content of a GD image resource using output buffering:
ob_start();
imagepng($image);
$pngdata = ob_get_clean();

image GD and png masking

what would be basic code for masking one image with another in GD - one image with black shape and transparent background would be used to crop another image - a photo so that photo is in the shape of black image.
One way to do it is using phpThumb.
Basic reference here: http://phpthumb.sourceforge.net/demo/demo/phpThumb.demo.demo.php#x31
If creating the new image on the fly it would be something as simple as:
<img src="../phpThumb.php?src=path/to/image/image.jp&fltr[]=mask|path/to/mask/mask.png&f=png" alt="">
To output into a png.
If doing this after an image upload to create a new image to be stored on the server, first figure out the basics of phpThumb and then set the mask parameters with all the rest:
For example:
...
require_once('phpThumb/phpthumb.class.php');
//Begin phpThumb work to resize image and create thumbnail
$uploaddir = $_SERVER['DOCUMENT_ROOT'] . $destination;
$uploadfile = $uploaddir . $file;
$phpThumb = new phpThumb();
// set data source -- do this first, any settings must be made AFTER this call
$phpThumb->setSourceFilename($uploadfile);
$phpThumb->setParameter('w', 360); //change to update the picture size
$phpThumb->setParameter('h', 470); //change to update the picture size
$phpThumb->setParameter('fltr[]', 'mask|path/to/mask/mask.png'); //set mask
$phpThumb->setParameter('f', 'png'); //set png output format
$outputdir = $_SERVER['DOCUMENT_ROOT'] . $destination;
$output_filename = $outputdir . "masked" . $file;
$phpThumb->setParameter('config_allow_src_above_docroot', true);
if ($phpThumb->GenerateThumbnail()) { // this line is VERY important, do not remove it!
if ($phpThumb->RenderToFile($output_filename)) {
...

Categories