I'm working with Laravel 9 and Image Intervention 2.7 and I wanted to resize uploaded images.
Here is the upload method:
public static function upload($file,$cat,$queid)
{
...
if (in_array($file->getClientOriginalExtension(), self::resizeable())) {
$file->storeAs(self::route(), $fileName);
$custom = self::resize($file, $fileName);
}
$file->storeAs(self::route(), $fileName);
...
}
So I call the static function reszie which goes here:
public static function resize($file, $fileName)
{
$path = self::route();
foreach (self::size() as $key => $value) {
$resizePath = self::route() . "{$value[0]}x{$value[1]}_" . $fileName;
Image::make($file->getRealPath())
->resize($value[0], $value[1], function ($constraint) {
$constraint->aspectRatio();
})
->save($resizePath);
$urlResizeImage[] = ["upf_path" => $resizePath, "upf_dimension" => "{$value[0]}x{$value[1]}"];
}
self::$urlResizeImage = $urlResizeImage;
}
As you can see I pass the $resizePath as $path to save method of Image Intervention Facade:
public function save($path = null, $quality = null, $format = null)
{
$path = is_null($path) ? $this->basePath() : $path;
if (is_null($path)) {
throw new NotWritableException(
"Can't write to undefined path."
);
}
if ($format === null) {
$format = pathinfo($path, PATHINFO_EXTENSION);
}
$data = $this->encode($format, $quality);
$saved = #file_put_contents($path, $data);
if ($saved === false) {
throw new NotWritableException(
"Can't write image data to path ({$path})"
);
}
// set new file info
$this->setFileInfoFromPath($path);
return $this;
}
But now the problem is with file_put_contents which does not generate the resized images.
And also no errors returned and just the original image will be saved!
So what's going wrong here? How can I properly resize the original image and save it to the directory?
I would really appreciate any idea or suggestion from you guys about this...
Related
When I try to upload images in dropzone from my localhost then I get ERROR! but on server I can upload this successful.This problem made me difficult to test product.
and this is my code
public function storeMedia(Request $request)
{
//resize image
$path = storage_path('tmp/uploads');
$imgwidth = 1000;
$imgheight = 1000;
if (!file_exists($path)) {
mkdir($path, 775, true);
}
$file = $request->file('file');
$name = uniqid() . '_' . trim($file->getClientOriginalName());
$full_path = storage_path('tmp/uploads/' . $name);
$img = \Image::make($file->getRealPath());
if ($img->width() > $imgwidth || $img->height() > $imgheight) {
$img->resize($imgwidth, null, function ($constraint) {
$constraint->aspectRatio();
});
}
$img->save($full_path);
}
I think maybe about permission but i'm not sure. I really don't know to solve this problem please help me
I'm working with laravel 7 and using intervention/image to store images. However, I want to encode and store images as webp, I'm using the following code but it is not encoding the image in webp rather it is storing in the original format. Can you please tell me what I'm doing wrong?
public function storePoster(Request $request, Tournament $tournament)
{
if ($request->hasFile('poster')) {
$tournament->update([
'poster' => $request->poster->store('images', ['disk' => 'public_uploads']),
]);
$image = Image::make(public_path('uploads/' . $tournament->poster))->encode('webp', 90)->resize(200, 250);
$image->save();
}
}
Try this :
public function storePoster(Request $request, Tournament $tournament)
{
if ($request->hasFile('poster')) {
$tournament->update([
'poster' => $request->poster->store('images', ['disk' => 'public_uploads']),
]);
$classifiedImg = $request->file('poster');
$filename = $classifiedImg->getClientOriginalExtension();
// Intervention
$image = Image::make($classifiedImg)->encode('webp', 90)->resize(200, 250)->save(public_path('uploads/' . $filename . '.webp')
}
}
This is my code to convert to .webp and resize (keep image's ratio)
$imageResize = Image::make($image)->encode('webp', 90);
if ($imageResize->width() > 380){
$imageResize->resize(380, null, function ($constraint) {
$constraint->aspectRatio();
});
}
$destinationPath = public_path('/imgs/covers/');
$imageResize->save($destinationPath.$name);
if you want to convert image in to WEBP without any service or package, try this method. work for me. have any question can ask. Thankyou
$post = $request->all();
$file = #$post['file'];
$code = 200;
$extension = $file->getClientOriginalExtension();
$imageName = $file->getClientOriginalName();
$path = 'your_path';
if(in_array($extension,["jpeg","jpg","png"])){
//old image
$webp = public_path().'/'.$path.'/'.$imageName;
$im = imagecreatefromstring(file_get_contents($webp));
imagepalettetotruecolor($im);
// have exact value with WEBP extension
$new_webp = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp', $webp);
//del old image
unlink($webp);
// set qualityy according to requirement
return imagewebp($im, $new_webp, 50);
}
I'm trying to create a image upload function for my e-commerce website. This is the function I used to upload files,
Image upload function
private function upload_product_image($name, $file) {
$this->load->library('upload');
$dir = $name;
if (!is_dir('store/' . $dir)) {
mkdir('store/' . $dir, 777, true);
}
$config['upload_path'] = './store/' . $dir . '/';
$config['allowed_types'] = 'jpg|png';
$config['encrypt_name'] = TRUE;
$this->upload->initialize($config);
if (!$this->upload->do_upload($file)) {
return null;
} else {
if (is_file($config['upload_path'])) {
chmod($config['upload_path'], 777);
}
$ud = $this->upload->data();
$source = $ud['full_path'];
$destination = $ud['full_path'];
$image = imagecreatefromjpeg($source);
imagejpeg($image, $destination, 75);
return $config['upload_path'] . $ud['file_name'];
}
}
Save product
public function save_product(){
*** other code ****
$dir = date('Ymdhis');
$dir = url_title($dir, 'dash', true);
$this->upload_product_image($dir, 'add-product-image1'),
*** other code ****
}
There are couple of issues when running this function,
Image is not uploaded in first attempt ( Add new product )
But It created the product folder
If I update the product images It is working fine.
If you could show me, what is the wrong with this code It'll be really helpful.
Thank you so much
I installed the patch "intervention/image", "must-master" in order to make my image to reduce the size of it to 300 by 300.
I've done some forms and appears to me always the same mistake.
Call to a member function resize() on string
which got the error?
Controller
public function updateProfile() {
$file = Input::file('imagem');
$profileData = Input::except('_token');
$validation = Validator::make($profileData, User::$profileData);
if ($validation->passes()) {
if ($file == null) {
User::where('id', Input::get('id'))->update($profileData);
Session::flash('message', 'Perfil editado com sucesso');
return view('backend/perfil.index');
}
$file = array_get($profileData,'imagem');
$destinationPath = 'imagens/perfil';
$extension = $file->getClientOriginalExtension();
$filename = rand(11111, 99999) . '.' . $extension;
$reduzir = $filename -> resize (300,300);
$profileData['imagem'] = $filename;
$upload_success = $file->move($destinationPath, $filename);
User::where('id', Input::get('id'))->update($profileData);
Session::flash('message', 'Perfil editado com sucesso');
return Redirect::to('backend/perfil');
} else {
return Redirect::to('backend/perfil')->withInput()->withErrors($validation);
}
}
The issue might be because of these reasons
Have you added this aliases in your app.php
'aliases' => [
//add these three at the bottom
'Form' => Illuminate\Html\FormFacade::class,
'HTML' => Illuminate\Html\HtmlFacade::class,
'Image' => Intervention\Image\Facades\Image::class
],
I believe that you already have form and html helper.
And use this function in the Controller
i.e., just pass the image and size value as the Parameter to this function
In the controller you have just call the below function like
$resizedImage = $this->resize($image, $request->get('image_size'));
And the resize() function was given below
private function resize($image, $size)
{
try
{
$extension = $image->getClientOriginalExtension();
$imageRealPath = $image->getRealPath();
$thumbName = 'thumb_'. $image->getClientOriginalName();
//$imageManager = new ImageManager(); // use this if you don't want facade style code
//$img = $imageManager->make($imageRealPath);
$img = Image::make($imageRealPath); // use this if you want facade style code
$img->resize(intval($size), null, function($constraint) {
$constraint->aspectRatio();
});
return $img->save(public_path('images'). '/'. $thumbName);
}
catch(Exception $e)
{
return false;
}
How to auto resize the image uploaded to this foder: 'assets/media/':
<?php defined('SYSPATH') OR die('No direct access allowed.');
class Uploader_Controller extends Controller_Core {
public function bulkUpload() {
Kohana::log('debug', 'Start to upload');
$files = Validation::factory($_FILES)
->add_rules('picture', 'upload::valid', 'upload::required', 'upload::type[gif,jpg,png,jpeg]', 'upload::size[10M]');
Kohana::log('debug', 'Start to validate');
if ($files->validate()) {
Kohana::log('debug', 'validate passed');
$filename = upload::save('picture');
$thumbSize = Kohana::config('upload.thumb_size');
Image::factory($filename)
->resize($thumbSize[0], $thumbSize[1], Image::WIDTH)
->save(DOCROOT . 'assets/media/thumbs/' . basename($filename));
$partName = explode('/', $filename);
$picture = $partName[count($partName) - 1];
$data['name'] = '';
$data['picture'] = $picture;
$data['category_id'] = $this->input->post('category_id', 0);
$data['description'] = '';
;
$data['user_id'] = $this->input->post('user_id', 0);
$pictureModel = new Picture_Model();
try {
$photo = $pictureModel->savePicture($data);
echo url::site('assets/media/' . $picture);
} catch (Exception $e) {
}
}
}
}
i have add this line but still not working:
$filename->resizeToWidth(300);
You are not using the Kohana image and upload library properly. The docs have some examples on how to use the Kohana image upload and resize library:
Upload and resize
Cropping Profile Images
Docs on how to use the image library
You can resize and save an image with to following code:
Image::factory($filename)
->resize(300, NULL, Image::AUTO)
->save($your_save_path);