Saving animated gif with image intervention - laravel

I am trying to upload animated gif as user avatar. These images are converted to base64 through javascript and then are uploaded using image intervention.
$img = Image::make(file_get_contents($file));
$mime = $img->mime();
if ($mime == 'image/jpeg')
$ext= '.jpg';
elseif ($mime == 'image/png')
$ext= '.png';
elseif ($mime == 'image/gif')
$ext= '.gif';
elseif($mime == 'image/x-icon')
$ext = '.ico';
elseif($mime == 'image/bmp')
$ext = '.bmp';
else {
$ext = '.jpg';
}
$name = time().$ext;
$path = public_path("images/$controller");
File::isDirectory($path) or File::makeDirectory($path);
if(property_exists($field, 'size') && !$ext=='.gif') {
$field->size = explode('*',$field->size);
if($img->resize($field->size[0], $field->size[1])->save("$path/$name")) {
$data[$key] = $name;
} else {
$data[$key] = null;
}
} else {
if($img->save("$path/$name")) {
$data[$key] = $name;
} else {
$data[$key] = null;
}
}
But, those images lose animation after upload. I don't know what to do. How to not lose animation?
Javascript code:
reader.onload = function(e) {
var src = e.target.result;
var name = file.name;
var type = file.type;
var img = "<img src='"+src+"' class='img-fluid mx-auto' alt='image'>";
$('.card_group_'+field+' .previewContainer_'+count+' .file-loading').remove();
$('.card_group_'+field+' .previewContainer_'+count+' .imagePreview').append(img);
$('.card_group_'+field+' .previewContainer_'+count+' .card-header').append(name);
var input = "input[name='"+field+"']";
var added = $(input).val();
if(added == '') {
$(input).val(src);
} else {
$(input).val(added+';'+src);
}
}
reader.readAsDataURL(file);

For now, you can use another function to save when it is a gif, and keep using others from the library.
if ($file->getClientOriginalExtension() == 'gif') {
copy($file->getRealPath(), $destination);
}
else {
$image->save($destination);
}
$width = $image->width();
$height = $image->height();
$image->destroy();
Credits to: https://github.com/Intervention/image/issues/176#issuecomment-58863939

Related

how to create a thumbnail while saving the image

i have this code where the user uploaded image is saved.
is it possible in the meantime to create a thumbnail?
function saveImages($dataArray, $idArticles, $folderPath, $prefixFile){
$folderPathDefault = '../../media/articles/imm'.$idArticles.'/';
$prefixFileDefault = 'photo_';
if($folderPath == null){
$folderPath = $folderPathDefault;
array_map('unlink', array_filter((array) glob($folderPath."*")));
}
if($prefixFile == null){
$prefixFile = $prefixFileDefault;
}
if (!is_dir($folderPath)) {
// dir doesn't exist, make it
mkdir($folderPath);
}
$count = 1;
foreach ($dataArray as $data) {
$image_parts = explode(";base64,", $data);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = $folderPath . $prefixFile . $count . '.jpg';
file_put_contents($file, $image_base64);
$count ++;
}
}
Thank you
For those interested or solved with this function:
function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
function saveImages($dataArray, $idArticles, $folderPath, $prefixFile){
$folderPathDefault = '../../media/articles/imm'.$idArticles.'/';
$prefixFileDefault = 'photo_';
if($folderPath == null){
$folderPath = $folderPathDefault;
array_map('unlink', array_filter((array) glob($folderPath."*")));
}
if($prefixFile == null){
$prefixFile = $prefixFileDefault;
}
if (!is_dir($folderPath)) {
// dir doesn't exist, make it
mkdir($folderPath);
}
$count = 1;
foreach ($dataArray as $data) {
$image_parts = explode(";base64,", $data);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = $folderPath . $prefixFile . $count . '.jpg';
file_put_contents($file, $image_base64);
$count ++;
}
if (!file_exists('../../media/articles/imm'.$idArticles.'/thumbnail/')) {
mkdir('../../media/articles/imm'.$idArticles.'/thumbnail/', 0777, true);
}
$dir = "../../media/articles/imm".$idArticles."/thumbnail/";
array_map('unlink', glob("{$dir}*.jpg"));
$immagine= "../../media/articles/imm".$idArticles."/";
$files = glob("$immagine*.*");
$uno= 1;
for ($i=0; $i<count($files); $i++) {
$image = $files[$i];
$url = $image;
$imgResize = resize_image($url, 360, 270);
$path = '../../media/articles/imm'.$idArticles.'/thumbnail/thumbnail_photo_'.$uno++.'.jpg';
imagejpeg($imgResize, $path);
}
}

upload multiple image in flutter app to a laravel api

Here is my function in flutter
I have use multi_image_picker to pick images sand i have save them in that variable images. Now I want post those images in laravel api. But this don't work.
if(images != null ){
try{
List<MultipartFile> allMultiFiles = [];
for (Asset asset in images) {
ByteData byteData = await asset.getByteData();
List<int> imageData = byteData.buffer.asUint8List();
print(imageData);
var multipartFile = new MultipartFile.fromBytes(
imageData,
filename: asset.name,
);
allMultiFiles.add(multipartFile);
}
FormData formData = FormData.fromMap({
'images' : allMultiFiles
});
var response = await dio.post(UPLOAD_URL, data:formData);
if(response.statusCode == 200){
print('done');
}else{
print('not save image. Error !!');
}
}catch (e){
print(e.toString());
}
}
}
Here is my function to store
public function save(Request $request){
if(!$request->hasFile('images')){
return response()->json([
'upload file not found' => 'not found'
],400);
}else{
$allowedExtension = ['jpg','jpeg','png'];
$files = $request->file('images');
$erros = [];
foreach ($files as $file){
$extension = $file->getClientOriginalExtension();
$check = in_array($extension,$allowedExtension);
if($check) {
foreach($request->images as $mediaFiles) {
$path = $mediaFiles->store('public/images');
$name = $mediaFiles->getClientOriginalName();
return response()->json([
'message' => 'images saved'
],200);
}
} else {
return response()->json(['invalid_file_format'], 422);
}
}
}
}
It not work, images are not saved.
I'm beginner in flutter and thanks for your help.

I get this error when trying to verify the email of candidates, Array to String conversion

I have a laravel system that when someone registers, they get a link on their emails where they have to click on it to verify their email. Once they click the link, their information is stored in the users table and the candidates table.
However, values are only inserted in the users table and not the candidates table, and I get the error "Array to string conversion".
Also, the link works well in local host but not after hosting the system.
RegisiterController.php
Str.php`
public function registerCandidate(Request $request){
if(setting('general_enable_candidate_registration')!=1){
return abort(401);
}
$rules = [
'first_name'=>'required',
'last_name'=>'required',
'national_id'=>'required',
'gender'=>'required',
'email'=>'required|email|string|max:255|unique:users',
'date_of_birth_year'=>'required',
'date_of_birth_month'=>'required',
'date_of_birth_day'=>'required',
'categories'=>'required',
'picture' => 'nullable|max:'.config('app.upload_size').'|mimes:jpeg,png,gif',
'cv_path' => 'nullable|max:'.config('app.upload_size').'|mimes:'.config('app.upload_files'),
];
if(setting('general_candidate_captcha')==1){
$rules['captcha'] = 'required|captcha';
}
foreach(CandidateFieldGroup::where('registration',1)->orderBy('sort_order')->get() as $group){
foreach($group->candidateFields as $field){
if($field->type=='file'){
$required = '';
if($field->required==1){
$required = 'required|';
}
$rules['field_'.$field->id] = 'nullable|'.$required.'max:'.config('app.upload_size').'|mimes:'.config('app.upload_files');
}
elseif($field->required==1){
$rules['field_'.$field->id] = 'required';
}
}
}
$this->validate($request,$rules);
$requestData = $request->all();
$password= $request->password;
$requestData['name']= $request->first_name.' '.$request->last_name;
$requestData['display_name'] = $request->first_name;
$requestData['password'] = Hash::make($password);
$requestData['role_id'] = 3;
$fields = CandidateField::get();
//check if email verification is required
if(setting('general_candidate_verification')==1){
do{
$hash = Str::random(30);
}while(PendingUser::where('hash',$hash)->first());
$formData = $_POST;
$formData['name'] = $request->first_name.' '.$request->last_name;
$formData['display_name'] = $request->first_name;
$formData['role_id'] = 3;
if($request->hasFile('picture')) {
$path = $request->file('picture')->store(PENDING_USER_FILES,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$img = Image::make($file);
$img->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($file);
$formData['picture'] = $file;
}
else{
$formData['picture'] =null;
}
if($request->hasFile('cv_path')) {
//$path = $request->file('cv_path')->store(CANDIDATES,'public_uploads');
$name = $_FILES['cv_path']['name'];
$extension = $request->cv_path->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = uniqid().'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('cv_path')->storeAs(PENDING_USER_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$formData['cv_path'] = $file;
}
else{
$formData['cv_path'] =null;
}
$pendingUser = PendingUser::create([
'role_id'=>3,
'data'=> serialize($formData),
'hash'=> $hash
]);
//scan for files
foreach($fields as $field){
if(isset($requestData['field_'.$field->id]) && $field->type=='file' && $request->hasFile('field_'.$field->id))
{
//generate name for file
$name = $_FILES['field_'.$field->id]['name'];
//dd($name);
$extension = $request->{'field_'.$field->id}->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = $pendingUser->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('field_'.$field->id)->storeAs(PENDING_USER_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$pendingUser->pendingUserFiles()->create([
'file_name'=>$_FILES['field_'.$field->id]['name'],
'file_path'=>$file,
'field_id'=>$field->id
]);
}
}
//send email to user
$link = route('confirm.candidate',['hash'=>$hash]);
$this->sendEmail($request->email,__('site.confirm-your-email'),__('site.confirm-email-mail',['link'=>$link]));
return redirect()->route('register.confirm');
}
//First create user
$user= User::create($requestData);
//Calculate date of birth
$dateOfBirth = $request->date_of_birth_year.'-'.$request->date_of_birth_month.'-'.$request->date_of_birth_day;
$requestData['date_of_birth'] = $dateOfBirth;
//checkfor picture
if($request->hasFile('picture')) {
$path = $request->file('picture')->store(CANDIDATES,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$img = Image::make($file);
$img->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($file);
$requestData['picture'] = $file;
}
else{
$requestData['picture'] =null;
}
if($request->hasFile('cv_path')) {
//$path = $request->file('cv_path')->store(CANDIDATES,'public_uploads');
$name = $_FILES['cv_path']['name'];
$extension = $request->cv_path->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('cv_path')->storeAs(CANDIDATE_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$requestData['cv_path'] = $file;
}
else{
$requestData['cv_path'] =null;
}
$user->candidate()->create($requestData);
//save categories
$user->candidate->categories()->attach($request->categories);
//now save custom fields
$customValues = [];
//attach custom values
foreach($fields as $field){
if(isset($requestData['field_'.$field->id]))
{
if($field->type=='file'){
if($request->hasFile('field_'.$field->id)){
//generate name for file
$name = $_FILES['field_'.$field->id]['name'];
$extension = $request->{'field_'.$field->id}->extension();
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('field_'.$field->id)->storeAs(CANDIDATE_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$customValues[$field->id] = ['value'=>$file];
}
}
else{
$customValues[$field->id] = ['value'=>$requestData['field_'.$field->id]];
}
}
}
$user->candidateFields()->sync($customValues);
$message = __('mails.new-account',[
'siteName'=>setting('general_site_name'),
'email'=>$requestData['email'],
'password'=>$password,
'link'=> url('/login')
]);
$subject = __('mails.new-account-subj',[
'siteName'=>setting('general_site_name')
]);
$this->sendEmail($requestData['email'],$subject,$message);
//now login user
Auth::login($user, true);
//redirect to relevant page
if(session()->exists('candidate_destination')){
$url = session()->get('candidate_destination');
session()->remove('candidate_destination');
return redirect($url);
}
else{
return redirect()->route('home');
}
}
public function confirmCandidate($hash){
//get pending user
$pendingUser = PendingUser::where('hash',$hash)->first();
if(!$pendingUser){
abort(404);
}
$requestData = unserialize($pendingUser->data);
$password = $requestData['password'];
$requestData['password'] = Hash::make($password);
//check for profile picture and move to new directory
if(!empty($requestData['picture']) && file_exists($requestData['picture'])){
$file = basename($requestData['picture']);
$newPath = UPLOAD_PATH.'/'.CANDIDATES.'/'.$file;
rename($requestData['picture'],$newPath);
$requestData['picture'] = $newPath;
}
if(!empty($requestData['cv_path']) && file_exists($requestData['cv_path'])){
$file = basename($requestData['cv_path']);
$newPath = UPLOAD_PATH.'/'.CANDIDATE_FILES.'/'.$file;
rename($requestData['cv_path'],$newPath);
$requestData['cv_path'] = $newPath;
}
//First create user
$user= User::create($requestData);
//Calculate date of birth
$dateOfBirth = $requestData['date_of_birth_year'].'-'.$requestData['date_of_birth_month'].'-'.$requestData['date_of_birth_day'];
$requestData['date_of_birth'] = $dateOfBirth;
$user->candidate()->create($requestData);
//save categories
if(isset($requestData['categories'])){
$user->candidate->categories()->attach($requestData['categories']);
}
$fields = CandidateField::get();
$customValues = [];
//attach custom values
foreach($fields as $field){
if($field->type=='file'){
$pendingFile = $pendingUser->pendingUserFiles()->where('field_id',$field->id)->first();
if($pendingFile){
//generate name for file
$name = $pendingFile->file_name;
$info = new \SplFileInfo($name);
$extension = $info->getExtension();
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$file = UPLOAD_PATH.'/'.CANDIDATE_FILES.'/'.$name;
rename($pendingFile->file_path,$file);
$customValues[$field->id] = ['value'=>$file];
}
}
elseif(isset($requestData['field_'.$field->id])){
$customValues[$field->id] = ['value'=>$requestData['field_'.$field->id]];
}
}
$user->candidateFields()->sync($customValues);
$pendingUser->delete();
$message = __('mails.new-account',[
'siteName'=>setting('general_site_name'),
'email'=>$requestData['email'],
'password'=>$password,
'link'=> url('/login')
]);
$subject = __('mails.new-account-subj',[
'siteName'=>setting('general_site_name')
]);
$this->sendEmail($requestData['email'],$subject,$message);
//now login user
Auth::login($user, true);
//redirect to relevant page
if(session()->exists('candidate_destination')){
$url = session()->get('candidate_destination');
session()->remove('candidate_destination');
return redirect($url);
}
else{
return redirect()->route('home');
}
}
`

Arabic language not working on pdf export using dompdf, while its working fine with excel in laravel

This is my controller stockcontroller.php, using for export data
public function exportStock(Request $request)
{
header('http-equiv : Content-Type; Content-Type: text/html; charset=utf-8');
if($request->status=='show')
{
$su=stock::where('is_active',1);
}
elseif ($request->status=='hide')
{
$su=stock::where('is_active',0);
}
else{
$su=stock::where('is_active','!=',2);
}
$su=$su->get();
$exp=$request->exp;
if($exp=='Export to Excel') {
$exp = 'XLS';
Excel::create('Export Data', function ($excel) use ($su) {
$excel->sheet('sheet 1', function ($sheet) use ($su) {
$sheet->appendRow(['S.No.', 'Stock Name(En)', 'Stock Name(Ar)', 'Users participated', 'Quantity', 'Status']);
$sn = 1;
foreach ($su as $p) {
if ($p->userQuantity()->first()) {
$temp = $p->userQuantity()->sum('quantity');
} else {
$temp = '';
}
if ($p->userStocks()->first()) {
$temp2 = $p->userStocks()->count();
} else {
$temp2 = '';
}
if ($p->is_active == '1') {
$st = 'Show';
} elseif ($p->is_active == '0') {
$st = 'Hide';
}
$sheet->appendRow([$sn, $p->name_en, $p->name_ar, $temp, $temp2, $st]);
$sn++;
}
});
})->download($exp);
return redirect('admin/stock');
}
if($exp=='Export to PDF'){$exp='PDF';
include ('dompdf/autoload.inc.php');
// instantiate and use the dompdf class
$var="<table><tr><th>S.No.</th><th>Stock Name(En)</th><th>Stock Name(Ar)</th><th>Users participated</th><th>Quantity</th><th>Status</th></tr>";
$tt=1;
foreach ($su as $dd) {
if ($dd->userQuantity()->first()) {
$temp = $dd->userQuantity()->sum('quantity');
} else {
$temp = '';
}
if ($dd->userStocks()->first()) {
$temp2 = $dd->userStocks()->count();
} else {
$temp2 = '';
}
if ($dd->is_active == '1') {
$st = 'Show';
} elseif ($dd->is_active == '0') {
$st = 'Hide';
}
$var .= "<tr><td>$tt</td><td>$dd->name_en</td><td>$dd->name_ar</td><td>$temp</td><td>$temp2</td><td>$st</td></tr>";
$tt++;
}
$var.="</table>";
$dompdf = new Dompdf();
$dompdf->loadHtml($var);
// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to Browser
$dompdf->stream();
}
}
Excel is working fine while PDF is not supporting Arabic content it
shows ????? like symbols in place of Arabic language. Note :
Previously I was using same code for pdf and excel there was the same
issue. So I try to make it separate from excel
I am able to fix the issue by using mpdf library.
Use the mpdf library. use this package in laravel.
Use the font-family: "XB Riyaz".
http://www.solutionsbased.in/laravel-arabic-content-display-issue-in-the-pdf/

CodeIgniter: I can’t to insert file_name image in database

That's code is in my controller… i can`t to insert name of image in database, except to upload in directory /uploads/
code for insertion file_name of image is below: $data[‘file_name’] = $_POST[‘file_name’];
please help me because needed for quickly.. thank you very much
public function edit ($id = NULL)
{
// Fetch a article or set a new one
if ($id) {
$this->data[‘article’] = $this->article_m->get($id);
count($this->data[‘article’]) || $this->data[‘errors’][] = ‘article could not be found’;
}
else {
$this->data[‘article’] = $this->article_m->get_new();
}
// Set up the form
$rules = $this->article_m->rules;
$this->form_validation->set_rules($rules);
// Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->article_m->array_from_post(array(
‘cat_id’,
‘title’,
‘url’,
‘body’,
‘pubdate’
));
/*
* upload
*/
$config[‘upload_path’] = ‘c:/wamp/www/uploads/’;
$config[‘allowed_types’] = ‘gif|jpg|png’;
$config[‘max_size’] = ‘1000’;
$config[‘max_width’] = ‘10240’;
$config[‘max_height’] = ‘7680’;
$field_name = “file_name”;
$this->load->library(‘upload’, $config);
if( $this->upload->do_upload($field_name)){
print “uploaded”;
die(“uploaded”);
} else {
$error = array(‘error’ => $this->upload->display_errors());
print_r($error);
die();
}
//end of upload
//insert file_name
$data[‘file_name’] = $_POST[‘file_name’];
$this->article_m->save($data, $id);
}
// Load the view
$this->data[‘subview’] = ‘admin/article/edit’;
$this->load->view(‘admin/_layout_main’, $this->data);
}
You may try something like this
if( $this->upload->do_upload($field_name) )
{
// get upload data
$upload_data = $this->upload->data();
$data[‘file_name’] = $upload_data['file_name'];
$this->article_m->save($data, $id);
//...
}
else
{
//...
}

Resources