Only first image uploaded, Upload multiple images individually in Laravel - php

Laravel Newbie here, would like to ask how to upload multiple images one by one. Multiple images work in one selection but putting images one by one to upload doesn't work and the first image only appears after submitting. Please help.
CONTROLLER
if (\Input::file('photos')) {
$base_path =
dirname(__FILE__) . "/../../../../uploads/img/gallery/" . $add->id . "/";
ini_set('gd.jpeg_ignore_warning', 1);
//get last uploaded file name
$files = (\Input::file('photos'));
$list_image = $temp = explode(",", $request->list_image);
foreach ($files as $key => $value) {
if (!is_null($value)) {
$temp = explode(".", $value->getClientOriginalName());
$newfilename = $value->getClientOriginalName();
if (!file_exists($base_path)) {
mkdir($base_path);
chmod($base_path, 0777);
}
$key = array_search($newfilename, $list_image);
if ($key == 0) {
$newfilename = $add->id . '_primary' . '.' . end($temp);
} else {
$newfilename = chr(64 + $key) . '_' . $newfilename;
}
$image = \Image::make($value);
// perform orientation using intervention
$image->orientate();
$new_width = $image->width();
$new_height = $image->height();
if ($new_width > 800) {
$percent = 0.7;
$new_width = $new_width * $percent;
$new_height = $new_height * $percent;
}
// resize image to fixed size
$image->resize($new_width, $new_height);
// create a new Image instance for inserting
$watermark = \Image::make(
public_path() . '/assets/img/icons/watermark.png',
);
// insert watermark at bottom-right corner with 10px offset
$image->insert(
public_path() . '/assets/img/icons/watermark.png',
'bottom-right',
10,
10,
);
$image->save($base_path . $newfilename);
}
}
}

You can do something like this.
$list_image = $temp = explode(",", $request->list_image);
if($request->hasfile('photos'))
{
$destinationPath = public_path('uploads/img/gallery/'. $add->id.'/');
foreach($request->file('photos') as $k => $file)
{
$temp = explode(".", $file->getClientOriginalName());
$newfilename = $file->getClientOriginalName();
$key = array_search($newfilename, $list_image);
if ($key == 0) {
$newfilename = $add->id . '_primary' . '.' . end($temp);
} else {
$newfilename = chr(64 + $key) . '_' . $newfilename;
}
$name = $newfilename.'.'.$file->getClientOriginalExtension();
File::makeDirectory($destinationPath, $mode = 0777, true, true);
$file->move($destinationPath, $name);
$tdestinationPath = public_path('uploads/img/gallery/thumb'. $add->id.'/');
try {
$img = Image::make($file->getRealPath());
$img->resize(50, 50, function ($constraint) {
$constraint->aspectRatio();
})->save($tdestinationPath.'/'.$name);
$img->destroy();
} catch (Exception $e) {
$response_data=array('images'=>"",'success'=>0,'message'=>$e->getMessage());
}
$image_arr[] = $name;
}
$uploaded_img = implode(',',$image_arr);
if(!empty($hidden_property_img)){
$uploaded_img = $hidden_property_img.','.$uploaded_img;
}
$data['images'] = $uploaded_img;
}

Related

how can I loop over a multiple file upload then add to my json array?

I would like to loop through multiple file uploads and the add them to my json
This is what I currently have for one upload:
$file_prefix = md5_file($tmp_file);
$file_name = $file_prefix . "_" . rand(1000, 99999) . "_{$session_check_data['id']}".".jpg";
$target_file = $vehicle_image_folder . "/".$file_name;
list($width, $height, $type, $attr) = getimagesize($tmp_file);
$image = new \Gumlet\ImageResize($tmp_file);
if($width > 1200) {
$image->resizeToWidth(1200);
}
$image->save($target_file, IMAGETYPE_JPEG);
if ($this->request->get('upload_thumb')) {
$thumbnail_file = $vehicle_image_folder . "/thumb_".$file_name;
$this->app['monolog']->info("thumbs required");
$image = new \Gumlet\ImageResize($target_file);
$image->resizeToWidth(400);
$image->save($thumbnail_file, IMAGETYPE_JPEG);
}
Here is what I attempted to do:
$files = array();
$l = 3;
foreach ($tmp_file as $k => $l) {
$file_prefix = md5_file($k);
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
$counter = 1;
foreach ($files as $file) {
$count = $counter++;
$file_name = $file_prefix . "_" . rand(1000, 99999) . "_{$session_check_data['id']}".".jpg";
$target_file = $vehicle_image_folder . "/".$file_name;
list($width, $height, $type, $attr) = getimagesize($file);
$image = new \Gumlet\ImageResize($file);
if ($width > 1200) {
$image->resizeToWidth(1200);
}
$image->save($target_file, IMAGETYPE_JPEG);
if ($this->request->get('upload_thumb')) {
$thumbnail_file = $vehicle_image_folder . "/thumb_" . $file_name;
$this->app['monolog']->info("thumbs required");
$image = new \Gumlet\ImageResize($target_file);
$image->resizeToWidth(400);
$image->save($thumbnail_file, IMAGETYPE_JPEG);
}
}
then I would like to return the 3 images in my JSON in the loc, maybe loc1, loc2, loc3?:
return $this->app->json(['success' => 1, 'info' => 'uploaded', 'loc' => $file_name]);
I would like to be able to show the 3 images that have been uploaded

not able to insert image height and image width in database using codeigniter

This is my controller code:
if ($files != '0') {
//echo "1";
if (isset($is_anonymous)) {
$is_anonymous = $is_anonymous;
} else {
$is_anonymous = "0";
}
$file_ary = $this->Jayesh($_FILES['files']);
$post_Id = $this->post_m->add_new_post($is_anonymous, $college_id, $writepost, $post, $article, $askq, $user_id, curr_date(), $v_id, $art_title, $art_image, $art_domain, $art_url, $article);
foreach ($file_ary as $file) {
$srt = explode('.', $file['name']);
$ext = $this->getExtension($file['name']);
$fiel_name = uniqid() . date("YmdHis") . "." . $ext;
$mime = $file['type'];
if (strstr($mime, "video/") || strstr($mime, "application/")) {
$filetype = "video";
$sourcePath = $file['tmp_name'];
$targetPath = "images/medical_college_images/video/" . $fiel_name;
//move_uploaded_file($sourcePath, $targetPath);
$s3->putObjectFile($sourcePath, $bucket, $targetPath, S3::ACL_PUBLIC_READ);
} else if (strstr($mime, "image/")) {
$filetype = "image";
$sourcePath = $file['tmp_name'];
$targetPath = "images/medical_college_images/image/" . $fiel_name;
//move_uploaded_file($sourcePath, $targetPath);
$s3->putObjectFile($sourcePath, $bucket, $targetPath, S3::ACL_PUBLIC_READ);
} else if (strstr($mime, "audio/")) {
$filetype = "audio";
}
if (isset($_POST['user_id'])) {
$user_id = $_POST['user_id'];
if (!empty($user_id)) {
$user = $this->post_m->check_user_exist_timeline($user_id);
if (!empty($user)) {
if ($filetype == 'video') {
$image_info = getimagesize("https://medicalwale.s3.amazonaws.com/images/medical_college_images/video/" . $fiel_name);
$image_width = '0';
$image_height = '0';
$video_width = '300';
$video_height = '160';
}
if ($filetype == 'image') {
//echo "https://d2c8oti4is0ms3.cloudfront.net/images/healthwall_media/image/".$fiel_name;
$image_info = getimagesize("https://medicalwale.s3.amazonaws.com/images/medical_college_images/image/" . $fiel_name);
$image_width = $image_info[0];
$image_height = $image_info[1];
$video_width = '300';
$video_height = '160';
}
//exit();
/* $last_user_id = $this->post_m->insert_image_post_into_media($fiel_name, $filetype,curr_date());
if (!empty($last_user_id))
{ */
$result = $this->post_m->insert_image_post_into_post_media($post_Id, curr_date(), $image_width, $image_height, $video_height, $video_width, $fiel_name, $filetype);
//}
}
}
}
}
Model code:
public function insert_image_post_into_post_media($post_Id, $cdate, $image_width, $image_height, $video_height, $video_width, $fiel_name, $filetype) {
$sql = "INSERT INTO college_post_media( `post_id`,`type`, `source`, `img_height`, `img_width`, `video_height`, `video_width`, `created_at`, `updated_at`, `deleted_at`)
VALUES ('$post_Id','$filetype','$fiel_name','$image_height', '$image_width','$video_height', '$video_width', '$cdate','$cdate','$cdate')";
return $result = $this->db->query($sql);
}
I'm facing an issue when inserting img_height and img_width in to the table. It is going in empty.
Try getting the image size while it is still on your domain:
Excerpt:
} else if (strstr($mime, "image/")) {
$filetype = "image";
$sourcePath = $file['tmp_name'];
list($image_width, $image_height) = getimagesize($file['tmp_name']);
$targetPath = "images/medical_college_images/image/" . $fiel_name;
//move_uploaded_file($sourcePath, $targetPath);
$s3->putObjectFile($sourcePath, $bucket, $targetPath, S3::ACL_PUBLIC_READ);
}
Assuming that $file['tmp_name'] is a fully qualified path.
Then you can remove:
$image_info = getimagesize("https://medicalwale.s3.amazonaws.com/images/medical_college_images/image/" . $fiel_name);
$image_width = $image_info[0];
$image_height = $image_info[1];

Photo editing with url to get php

Hello how can i include url function in photo
function photoUpload($file)
{
$messages = '';
$t = [];
$i = 0;
try {
$input = array(
'files' => $file,
'type' => Input::get('type'),
'max' => 1,
);
$files = array($input['files']);
$image = \Image::make($file->getRealPath());
$bigpath = public_path() . '/pictures/contentPhoto/big/';
$mediumpath = public_path() . '/pictures/contentPhoto/medium/';
$thumbpath = public_path() . '/pictures/contentPhoto/thumb/';
$maxFile = $input['max'];
$image->backup();
$rules = array('file' => 'max:50000|mimes:png,gif,jpeg,jpg');
if( !is_array($files) )
return ['status'=>false, 'msg'=> 'Bir problem var!' ];
if(count($files)>$maxFile)
return ['status'=>false, 'msg'=> 'En az bir fotoğraf gerekli!' ];
$status = array();
foreach ($files as $file) {
$isim = md5(uniqid('', true));
$t[]['org_name'] = $file->getClientOriginalName();
$t[$i]['extension'] = $file->getClientOriginalExtension();
$t[$i]['remote_name'] = $isim . '.' . $t[$i]['extension'];
$t[$i]['path'] = $thumbpath;
$t[$i]['remote_name'] = $isim . '.' . $file->getClientOriginalExtension();
$validator = Validator::make(array('file' => $file), $rules, [], ['file' => $file->getClientOriginalName()]);
if ($validator->passes()) {
$t[$i]['info'] = '<li>' . $file->getClientOriginalName() . ' bu fotoğraf yüklendi.' . '</li>';
$t[$i]['result'] = true;
$t[$i]['remote_full_name'] = Config::get('app.url') . '' . Config::get('app.pictures_db') . '/contentPhoto/thumb/' . $t[$i]['remote_name'];
$status[] = 1;
if (!file_exists(public_path().'/pictures/contentPhoto/')) {
mkdir(public_path().'/pictures/contentPhoto/', 0777, true);
}
$post_photo=$_FILES['files']['name'];
$post_photo_tmp=$_FILES['files']['tmp_name'];
$ext = pathinfo($post_photo, PATHINFO_EXTENSION); // getting image extension
list($width_min,$height_min)=getimagesize($post_photo_tmp); // fetching original image width and height
$ratio = $width_min / $height_min;
// Big Size
$newwidth_min=700; // set compressing image width
$newheight_min=($height_min / $width_min) * $newwidth_min; // equation for compressed image height
$big = $image->resize($newwidth_min,$newheight_min);
$big->sharpen(18)->save($bigpath.$t[$i]['remote_name'],60);
$big->reset();
if($ratio < 1) {
$t[$i]['ratio'] = false;
// Medium Size
$newwidth_min=320; // set compressing image width
$newheight_min=($height_min / $width_min) * $newwidth_min; // equation for compressed image height
$medium = $image->resize($newwidth_min,$newheight_min);
$medium->sharpen(8)->save($mediumpath.$t[$i]['remote_name'],60);
$medium->reset();
// Thumb Size
$newwidth_min=220; // set compressing image width
$newheight_min=($height_min / $width_min) * $newwidth_min; // equation for compressed image height
$thumb = $image->resize($newwidth_min,$newheight_min);
$thumb->sharpen(8)->save($thumbpath.$t[$i]['remote_name'],60);
$thumb->reset();
} else {
$t[$i]['ratio'] = true;
// Medium Size
$targetHeight= 320;
$targetWidth = 240;
$imgWidth = $image->getWidth();
$imgHeight = $image->getHeight();
$verticalRatio = $targetHeight / $imgWidth;
$horizontalRatio = $targetWidth / $imgHeight;
$imgAvg = min($verticalRatio,$horizontalRatio);
$newHeight = $imgHeight * $imgAvg;
$newWidth = $imgWidth * $imgAvg;
$medium = $image->resize($newWidth,$newHeight);
$medium->fit(320,170)->sharpen(8)->save($mediumpath.$t[$i]['remote_name'],60);
$medium->reset();
// Thumb Size
$targetHeight= 320;
$targetWidth = 240;
$imgWidth = $image->getWidth();
$imgHeight = $image->getHeight();
$verticalRatio = $targetHeight / $imgWidth;
$horizontalRatio = $targetWidth / $imgHeight;
$imgAvg = min($verticalRatio,$horizontalRatio);
$newHeight = $imgHeight * $imgAvg;
$newWidth = $imgWidth * $imgAvg;
$thumb = $image->resize($newWidth,$newHeight);
$thumb->fit(320,170)->sharpen(8)->save($thumbpath.$t[$i]['remote_name'],60);
$thumb->reset();
}
$insertDb = DBDosya::insertPicture($file->getClientOriginalName(), $isim.'.'.$file->getClientOriginalExtension(), '' . Config::get('app.pictures') . '/', '.'.$file->getClientOriginalExtension() );
$t[$i]['id'] = $insertDb;
} else {
$t[$i]['result'] = false;
$mesajlar = $validator->messages();
$htmlMesaj = '';
foreach ($mesajlar->all('<li>:message</li>') as $mesaj) {
$htmlMesaj .= $mesaj;
}
$t[$i]['info'] = $htmlMesaj;
}
$messages .= $t[$i]['info'];
$i++;
}
$status = in_array(1, $status);
} catch (Exception $e) {
return ['status' => false, 'msg' => $messages . '<li>' . $e->getMessage() . '</li>',];
}
return ['status' => $status, 'msg' => $messages, 'data' => $t[0]];
}
It works properly in the files that come with this file.
But I get getRealPath () error when I get photo with url.
How can I handle the photo from the URL with this function

move_uploaded_file affects JPG image quality(colors)

I am trying to upload an image in a folder using the move_uploaded_file() function. The image usually is a JPG.
The problem is that the moving process somehow affects the image quality. To me mor eprecises, the colors are not the same between the file that i want to upload and the uploaded file.
So far i think the problem lies withing the move_uploaded_file() function, as the colors of the temp file are correct.
Here is my code and the images before and after the upload(the top one is before uploading and the bottom one ois after upload).
This kind of behaviour isn't accepted as the results need to be print ready.
if ($this->request->is('post')) {
if (!$this->request->data['TplElement']['file']) {
$tplElementImage['TplElementImage']['original_id'] = 0;
$tplElementImage['TplElementImage']['filepath'] = NULL;
$tplElementImage['TplElementImage']['filepath_hires'] = NULL;
$this->TplElementImage->save($tplElementImage);
}
else {
//create the directory
$path = APP.WEBROOT_DIR.DS.'uploads'.DS.'templates'.DS.$tplElement['TplElement']['tpl_asset_page_id'].DS.$tplElementImage['TplElementImage']['tpl_element_id'].DS.$elementID;
if ($this->make_path($path.DS.'dummy.txt')) {
$tplElementImage['TplElementImage']['original_file_name'] = $this->request->data['TplElement']['file']['name'];
$filename = session_id().'_'.time().'_'.$tplElementImage['TplElementImage']['original_file_name'];
if ($this->request->data['TplElement']['file']['size'] > 0) {
if(move_uploaded_file($this->request->data['TplElement']['file']['tmp_name'], $path.DS.$filename)) {
$tplElementImage['TplElementImage']['filepath'] = '/uploads' . '/' . 'templates' . '/' . $tplElement['TplElement']['tpl_asset_page_id'] . '/' . $tplElementImage['TplElementImage']['tpl_element_id'] . '/' . $elementID . '/' . $filename;
$imageSize = getimagesize($path . DS . $filename);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$zoom = 1;
$imageWidthMm = $imageWidth * 25.4 / 200;
$imageHeightMm = $imageHeight * 25.4 / 200;
$inBlockImageHeight = $imageHeight * $blockWidth / $imageWidth;
$inBlockImageWidth = $imageWidth * $blockHeight / $imageHeight;
if ($inBlockImageHeight < $blockHeight || $inBlockImageWidth < $blockWidth) {
$zoom = max($blockHeight / $imageHeightMm, $blockWidth / $imageWidthMm);
}
if ($zoom > 1) {
$this->Session->setFlash(__('Image too small'));
$this->redirect('/tpl_asset_pages/edit/' . $tplElement['TplElement']['tpl_asset_page_id']);
return;
}
$tplElementImage['TplElementImage']['zoom'] = $zoom;
$tplElementImage['TplElementImage']['original_width'] = $imageWidth;
$tplElementImage['TplElementImage']['original_height'] = $imageHeight;
$tplElementImage['TplElementImage']['top'] = 0;
$tplElementImage['TplElementImage']['left'] = 0;
$tplElementImage['TplElementImage']['original_id'] = 0;
$tplElementImage['TplElementImage']['filepath_hires'] = NULL;
$tplElementImage['TplElementImage']['max_zoom_value'] = $this->ElementImage->GetMaxZoom($imageWidth, $imageHeight, $blockWidth, $blockHeight);
if ($this->TplElementImage->save($tplElementImage)) {
$this->Session->setFlash(__('File successfully saved'));
} else {
$this->Session->setFlash("Unable to save data");
}
}else{
$this->Session->setFlash("Unable to move file");
}
}
else {
if ($this->request->data['TplElement']['file']['size'] > 0) {
$this->Session->setFlash("Unable to save uploaded file");
}
else {
$tplElementImage['TplElementImage']['filepath'] = NULL;
$this->TplElementImage->save($tplElementImage);
$this->Session->setFlash("Unable to save uploaded file");
}
}
}
else {
$this->Session->setFlash('Unable to create folder');
}
}
$this->redirect('/tpl_asset_pages/edit/'.$tplElement['TplElement']['tpl_asset_page_id']);
}
The problem has been fixed using Imagick to write the file.
$img = new Imagick($this->request->data['TplElement']['file']['tmp_name']);
$img->setImageFormat(substr(strrchr($tplElementImage['TplElementImage']['original_file_name'],'.'),1));
//stuff
if($img->writeImage($path.DS.$filename)) {
//stuff
}
//stuff

Cropping an image using php

I'm trying to crop an image when it has been uploaded. So far I've only managed to resize it but if an image is a rectangular shape then the image is squashed which doesn't look nice. I'm trying to get coding that I can use with the function that I currently have to resize. The ones that I'm seeing I have to change my function and I'm hoping not to do that.
Here is my function
function createThumbnail($filename) {
global $_SITE_FOLDER;
//require 'config.php';
$final_width_of_image = 82;
$height = 85;
$path_to_image_directory = $_SITE_FOLDER.'portfolio_images/';
$path_to_thumbs_directory = $_SITE_FOLDER.'portfolio_images/thumbs/';
if(preg_match('/[.](jpg)$/', $filename)) {
$im = imagecreatefromjpeg($path_to_image_directory . $filename);
} else if (preg_match('/[.](gif)$/', $filename)) {
$im = imagecreatefromgif($path_to_image_directory . $filename);
} else if (preg_match('/[.](png)$/', $filename)) {
$im = imagecreatefrompng($path_to_image_directory . $filename);
}
$ox = imagesx($im);
$oy = imagesy($im);
$nx = $final_width_of_image;
$ny = floor($oy * ($final_width_of_image / $ox));
//$ny = $height;
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
if(!file_exists($path_to_thumbs_directory)) {
if(!mkdir($path_to_thumbs_directory)) {
die("There was a problem. Please try again!");
}
}
imagejpeg($nm, $path_to_thumbs_directory . $filename);
$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
$tn .= '<br />Congratulations. Your file has been successfully uploaded, and a thumbnail has been created.';
echo $tn;
}
Here is my function.
<?php
function crop($file_input, $file_output, $crop = 'square',$percent = false) {
list($w_i, $h_i, $type) = getimagesize($file_input);
if (!$w_i || !$h_i) {
echo 'Unable to get the length and width of the image';
return;
}
$types = array('','gif','jpeg','png');
$ext = $types[$type];
if ($ext) {
$func = 'imagecreatefrom'.$ext;
$img = $func($file_input);
} else {
echo 'Incorrect file format';
return;
}
if ($crop == 'square') {
$min = $w_i;
if ($w_i > $h_i) $min = $h_i;
$w_o = $h_o = $min;
} else {
list($x_o, $y_o, $w_o, $h_o) = $crop;
if ($percent) {
$w_o *= $w_i / 100;
$h_o *= $h_i / 100;
$x_o *= $w_i / 100;
$y_o *= $h_i / 100;
}
if ($w_o < 0) $w_o += $w_i;
$w_o -= $x_o;
if ($h_o < 0) $h_o += $h_i;
$h_o -= $y_o;
}
$img_o = imagecreatetruecolor($w_o, $h_o);
imagecopy($img_o, $img, 0, 0, $x_o, $y_o, $w_o, $h_o);
if ($type == 2) {
return imagejpeg($img_o,$file_output,100);
} else {
$func = 'image'.$ext;
return $func($img_o,$file_output);
}
}
?>
And you can call like this
crop($file_input, $file_output, $crop = 'square',$percent = false);
And also resize function if you need.
<?php
function resize($file_input, $file_output, $w_o, $h_o, $percent = false) {
list($w_i, $h_i, $type) = getimagesize($file_input);
if (!$w_i || !$h_i) {
return;
}
$types = array('','gif','jpeg','png');
$ext = $types[$type];
if ($ext) {
$func = 'imagecreatefrom'.$ext;
$img = $func($file_input);
} else {
return;
}
if ($percent) {
$w_o *= $w_i / 100;
$h_o *= $h_i / 100;
}
if (!$h_o) $h_o = $w_o/($w_i/$h_i);
if (!$w_o) $w_o = $h_o/($h_i/$w_i);
$img_o = imagecreatetruecolor($w_o, $h_o);
imagecopyresampled($img_o, $img, 0, 0, 0, 0, $w_o, $h_o, $w_i, $h_i);
if ($type == 2) {
return imagejpeg($img_o,$file_output,100);
} else {
$func = 'image'.$ext;
return $func($img_o,$file_output);
}
}
?>
resize($file_input, $file_output, $w_o, $h_o, $percent = false);
You can use SimpleImage class found here SimpleImage
[edit] Updated version with many more features here SimleImage Updated
I use this when resizing various images to a smaller thumbnail size while maintaining aspect ratio and exact image size output. I fill the blank area with a colour that suits the background for where the image will be placed, this class supports cropping. Explore the methods cutFromCenter and maxareafill.
For example in your code you would not need to imagecreatefromjpeg() you would simply;
Include the class include('SimpleImage.php');
then;
$im = new SimpleImage();
$im->load($path_to_image_directory . $filename);
$im->maxareafill($output_width,$output_height, 0,0,0); // rgb
$im->save($path_to_image_directory . $filename);
I use this class daily and find it very versatile.

Categories