Laravel show error getimagesize on image update - php

I am having a strange issue here on image update. After add a new product I need the option of update image and get this error while inserting it everything is ok.
getimagesize(2.png): failed to open stream: No such file or directory
Here is my code
$file = $request->image;
if (isset($file))
{
list($width, $height) = getimagesize($file);
$extension = $file->getClientOriginalExtension();
$final_filename = $file->getFilename() . '.' . $extension;
$new_height_75 = (75 * $height) / $width;
$thumb_img_75 = Image::make($file->getRealPath())->resize(75, $new_height_75);
$thumb_img_75->save(public_path('attachments/product_images/thumbs_75').'/'.$final_filename,80);
$new_height_250 = (250 * $height) / $width;
$thumb_img_250 = Image::make($file->getRealPath())->resize(250, $new_height_250);
$thumb_img_250->save(public_path('attachments/product_images/thumbs_250').'/'.$final_filename,80);
$new_height_150 = (150 * $height) / $width;
$thumb_img_150 = Image::make($file->getRealPath())->resize(150, $new_height_150);
$thumb_img_150->save(public_path('attachments/product_images/thumbs_150').'/'.$final_filename,80);
Storage::disk('product_images')->put($final_filename, File::get($file));
$product->image = $final_filename;
}
If i dd($file ); it gets the file I want to upload.
Thanks

why not you try laravel validator to validate image type as well as image file size https://laravel.com/docs/5.4/validation#rule-image

Related

how to upload image directly on subdomain which is hosted on another server?

I am trying to upload my image directly to my subdomain which is hosted on another server
currently I am using this code to upload image in test.com to demo.test.com
$uploadDirectory = "//demo.test.com/";
i use this code to upload my image
$productname="sdf";
$member_id="123";
$uploadDirectory = "//demo.test.com/";
$randomNumber = rand(0, 99999);
$fn = $_FILES['image']['tmp_name'];
$size = getimagesize($fn);
$ratio = $size[0]/$size[1]; // width/height
$photo_name = $productname.'-'.md5($randomNumber.$member_id);
{
if( $ratio > 1) {
$width = 500;
$height = 500/$ratio;
}
else {
$width = 500*$ratio;
$height = 500;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor($width,$height);
$fileName3 = $uploadDirectory.$photo_name . '-500x500' . ".jpg";
imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst,$fileName3); // adjust format as needed
imagedestroy($dst);
}
What is the question ?
The subdomain is usually in the domain layer. This layer must not contains infrastructure logic (call to remote data provider). You shouldn't implement the upload in the Domain layer.
To upload your image, you have to call an interface (method : uploadImage) in the domain layer and implement it in the infrastructure (providers) layer.
see https://en.wikipedia.org/wiki/Single-responsibility_principle
and https://en.wikipedia.org/wiki/Dependency_inversion_principle

how to avoid duplicate upload in php?

i used from function crop_compress() to crop and compress image and then upload them
function crop_compress($source_url,$target_file,$qual) {
$image = imagecreatefromjpeg($source_url);
$width = imagesx($image);
$height = imagesy($image);
$thumb_width = $width;
$thumb_height = (9/16)*$width;
.
.
.
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
imagejpeg($thumb , $target_file,$qual);
return $target_file;}
$filename= 'crop_compress($_FILES["fileToUpload"]["tmp_name"][$key],$target_fileL,90)'
and it work fine.
now i want to upload this image with ftp and use ftp_put:
ftp_put($connecti,$target_file, $filename, FTP_BINARY);
and it work fine too, but it upload 2 times that i dont want.
one image in my directory and one with ftp
my question is how to avoid upload in my directory?
i know that ftp_put() and crop_compress() upload separately but i dont know which one should come first and how create a tmp_file to source in another or something else to avoid this problem?!
more info:
$target_dirL = "user"; #in the main host
$tempL=explode(".", $_FILES["fileToUpload"]["name"][$key]);
$target_fileL = $target_dir .$username1. '.' . end($tempL);
$target_dir = "user/$username/"; #another host
$temp=explode(".", $_FILES["fileToUpload"]["name"][$key]);
$target_file = $target_dir .$username1. '.' . end($temp);
$connecti = ftp_connect($anotherHost) or die('Couldn\'t connect to ftp server');
Use unlink( $filename ); after ftp_put($connecti,$target_file, $filename, FTP_BINARY);
This will delete the file after it had been uploaded via FTP.

Mysql php - how to deny image

how can we deny the image if the image does not correspond to a predetermined size image (using mysql php).
if users upload images and press the submit button, only the images that match the given size will be saved, but only if the picture does not match the size of the specified image will be denied
In php you will get image size :
for uploaded image :
$image_info = getimagesize($_FILES["file_field_name"]["tmp_name"]);
$image_width = $image_info[0];
$image_height = $image_info[1];
or
list($width, $height) = getimagesize('uploaded path of image');
echo "width: " . $width . "<br />";
echo "height: " . $height;
Put your condition on image height,width for deny image upload.
You can use getimagesize function to achive this:
<?php
$predefined_width = "100";
$predefined_height = "150";
list($width, $height) = getimagesize("myimg.jpg");
$w = $width;
$h = $height;
// at the time of upload image just check this if condition:
if($w == $predefined_width && $h == $predefined_height) {
// image upload code
}
?>

Efficient and fast image uploading

I've been playing around with a new website that will allow members to upload some content and images. I've knocked up the code html, php & mysql (with the help of google) and it now all works but not fast.
It could be my code is inefficient or my hosting company is restricting the uploading speed ... or both. I am very new to developing websites!
Using small size images <300kb is not an issue, but as soon as I use 6mb ones its can take up to 5minutes to upload the images even though I am reducing there size before upload. I've tested without database inserts so I know its the images part thats causing the issue.
Before I start looking at implementing DropBox to store the images ... has anyone come across this problem before that could recommend a different approach?
Code html snippet:
<form name="add-form" action="includes/new_post.php" method="post" enctype="multipart/form-data">
<input id='id_question_pic' name="upfile1[]" type="file" tabindex="3" multiple accept='image/*' max-uploads=6 />
Code in php:
//put all the uploaded images into an array
$files=array();
$fdata=$_FILES['upfile1'];
for($i=0;$i<count($fdata['name']);++$i){
$files[]=array(
'name' =>$fdata['name'][$i],
'type' => $fdata['type'][$i],
'tmp_name'=>$fdata['tmp_name'][$i],
'error' => $fdata['error'][$i],
'size' => $fdata['size'][$i]
);
}
//move to the correct directory, with unique file names
$directory = 'C:\Inetpub\vhosts\mydomain\form_uploads\\'; //use local server path (hosting company)
$dbimagepath = 'form_uploads/';
$result = true;
foreach ($files as $file) {
if ($file['error'] == 0) {
$filename = $file['name'];
if (strlen($filename) > 20) {$filename = substr($filename, strlen($filename) - 8);}
$filename = mt_rand() . '_' . $filename;
//ensure the filename is unique//
while (#getimagesize($directory . $filename)){$filename = mt_rand() . $filename;}
$fullpath = $directory . $filename;
if (exif_imagetype($file['tmp_name'])== 2){
$image = imagecreatefromstring(file_get_contents($file['tmp_name']));
//ORIGINAL DIMENTIONS
list( $width , $height ) = getimagesize($file['tmp_name']);
//ORIGINAL SCALE
$xscale=$width/600;
$yscale=$height/600;
//NEW DIMENSIONS WITH SAME SCALE
if ($yscale > $xscale)
{
$new_width = round($width * (1/$yscale));
$new_height = round($height * (1/$yscale));
}
else
{
$new_width = round($width * (1/$xscale));
$new_height = round($height * (1/$xscale));
}
//NEW IMAGE RESOURCE
if(!($imageResized = imagecreatetruecolor($new_width, $new_height)))
{//error handling}
//RESIZE IMAGE
if(! imagecopyresampled($imageResized, $image , 0 , 0 , 0 , 0 , $new_width , $new_height , $width , $height))
{//error handling}
$image = $imageResized;
$exif = exif_read_data($file['tmp_name']);
if (!empty($exif['Orientation']) || !$exif['Orientation']===null){
switch($exif['Orientation'])
{
case 3: // 180 rotate left
$image=imagerotate($image, 180, -1);
break;
case 6: // 90 rotate right
$image=imagerotate($image, -90, -1);
break;
case 8: // 90 rotate left
$image=imagerotate($image, 90, -1);
break;
default:
break;
}
}
if (imagejpeg($image, $fullpath, 80)){
//call function to update the database
}
imagedestroy($image);
}
else
{$result = false;}
}
}
Take a look at 3rd party solutions that are build to solve your particular problem.
Uploadcare for example.
With it you can have fast reliable uploads even without access to your host's filesystem and upload speed is limited only by your visitor's internet connectivity.

Why is my image rotating when resizing uploaded image in PHP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php resizing image on upload rotates the image when i don't want it to
I have created my first ever upload code and was testing it, the image resizes and uploads fine. The only issue I have is that it rotates.
Here is the code:
$errors = array();
$message = "";
if(isset($_POST["test"])){
$name = rand(1,999999) . $_FILES["uploadfile"]["name"];
$temp_name = $_FILES["uploadfile"]["tmp_name"];
$size = $_FILES["uploadfile"]["size"];
$extension = strtolower(end(explode('.', $_FILES['uploadfile']['name'])));
$path = "testupload/" . $name;
$info = getimagesize($temp_name);
$originalwidth = $info[0];
$originalheight = $info[1];
$mime = $info["mime"];
$acceptedHeight = 750;
$acceptedWidth = 0;
$acceptedMimes = array('image/jpeg','image/png','image/gif');
$acceptedfileSize = 4102314;
$acceptedExtensions = array('jpg','jpeg','gif','png');
echo $size;
// check mimetype
if(!in_array($mime, $acceptedMimes)){$errors[] = "mime type not allowed - The file you have just uploaded was a: " . $extension . " file!";}
if(!$errors){if($size > $acceptedfileSize){$errors[] = "filesize is to big - Your file size of this file is: " . $size;}}
if(!$errors){if(!in_array($extension, $acceptedExtensions)){$errors[] = "File extension not allowed - The file you have just uploaded was a: " . $extension . " file!";}}
if(!$errors){
// create the image from the temp file.
if ($extension === 'png'){
$orig = imagecreatefrompng($temp_name);
}elseif ($extension === 'jpeg'){
$orig = imagecreatefromjpeg($temp_name);
}elseif ($extension === 'jpg'){
$orig = imagecreatefromjpeg($temp_name);
}elseif ($extension === 'gif'){
$orig = imagecreatefromgif($temp_name);
}
// work out the new dimensions.
if ($acceptedHeight === 0){
$newWidth = $acceptedWidth;
$newHeight = ($originalheight / $originalwidth) * $acceptedWidth;
}else if ($acceptedWidth === 0){
$newWidth = ($originalwidth / $originalheight) * $acceptedHeight;
$newHeight = $acceptedHeight;
}else{
$newWidth = $acceptedWidth;
$newHeight = $acceptedHeight;
}
$originalwidth = imagesx($orig);
$originalheight = imagesy($orig);
// make ssure they are valid.
if ($newWidth < 1){ $newWidth = 1; }else{ $newWidth = round($newWidth ); }
if ($newHeight < 1){ $newHeight = 1; }else{ $newHeight = round($newHeight); }
// don't bother copying the image if its alreay the right size.
if ($originalwidth!== $newWidth || $originalheight !== $newHeight){
// create a new image and copy the origional on to it at the new size.
$new = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($new, $orig, 0,0,0,0, $newWidth, $newHeight, $originalwidth, $originalheight);
}else{
// phps copy on write means this won't cause any harm.
$new = $orig;
}
// save the image.
if ($extension === 'jpeg' || $extension === 'jpg'){
imagejpeg($new, $path, 100);
}else if ($save_ext === 'gif'){
imagegif($new, $path);
}else{
imagepng($new, $path, round(9 - (100 / (100 / 9))));
}
$message = $path;
Can someone please let me know what is going on?
Check the original image is actually in the orientation you expect. I work with images all day and the majority of the time it's Windows Photo Viewer showing the image in a certain orientation (reading an orientation change in the EXIF) but if you open it up in Photoshop it's different.
I tested your code with two images: one was landscape (width > height), the other was portrait (height > width). The code works.
The problem seems to be what #Tavocado said: newer cameras have a sensor to detect the orientation of the camera when the photo was taken, and they store that info in the photo. Also, newer photo viewing software reads that info back from the photo and rotates it before displaying the image. So you all the time see the image with the right orientation (sky up, earth down). However PHP functions (and the rest of the world) don't use that information and display the image as is was taken. That means that you will have to rotate yourself portrait images.
Just load your images in the browser (drag the file on the address bar) you you will see how the image is really stored in the file, without any automatic rotation.
The problem is that the image has embedded EXIF data, probably from the device that took the photo.
Investigate whether your images have embedded rotation information, using exif_read_data, and then auto-correct the rotation with a function like this.

Categories