Use Google Cloud Vision in Codeigniter, Cannot Find Class ImageAnnotatorClient - php

I want to implement the google cloud vision textDetection using a google cloud vision.
I have install the composer from google cloud vision to the thirdparty vendor in codeignier.
What my setup in construct is :
include APPPATH . 'third_party/vendor/autoload.php';
require_once APPPATH.'third_party/vendor/google/cloud-vision/src/V1/ImageAnnotatorClient.php';
and my function to call the OCR is :
function upload_ocr_image()
{
if (count($_FILES) === 0) { echo 'no image received from unity'; }
$phone_code = $this->input->post('phone_code', true);
$phone_number = $this->input->post('phone_number', true);
$allowedType = array(IMAGETYPE_GIF,IMAGETYPE_JPEG,IMAGETYPE_PNG);
$imgType = exif_imagetype($_FILES['ocr_image']['tmp_name']);
if(!in_array($imgType,$allowedType))
{
echo "Images Type Error. Images Type Only : GIF , JPEG, PNG";
exit;
}
else
{
//upload original size front end slider
$config['upload_path'] = './assets/ocr_image/';
$config['allowed_types'] = '*';
$config['file_name'] = $phone_code.$phone_number.".jpg";
$config['overwrite'] = TRUE;
$config['max_size'] = '8096';
$config['max_width'] = '8000';
$config['max_height'] = '8000';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if(!$this->upload->do_upload("ocr_image"))
{
echo "Maximum File Size Only 2 Mb Or Max Width = 2000 , Height = 2000";
exit;
}
else
{
$img_data = $this->upload->data();
// Authenticating with a keyfile path.
$imageAnnotator = new ImageAnnotatorClient([
'credentials' => base_url().'assets/google_cloud_vision/keyfile.json'
]);
# annotate the image
$response = $imageAnnotator->textDetection($img_data['full_path']);
$texts = $response->getTextAnnotations();
printf('%d texts found:' . PHP_EOL, count($texts));
foreach ($texts as $text) {
print($text->getDescription() . PHP_EOL);
# get bounds
$vertices = $text->getBoundingPoly()->getVertices();
$bounds = [];
foreach ($vertices as $vertex) {
$bounds[] = sprintf('(%d,%d)', $vertex->getX(), $vertex->getY());
}
print('Bounds: ' . join(', ',$bounds) . PHP_EOL);
}
$imageAnnotator->close();
}
}
}
But before process the text detection i have run into an error :
Fatal error: Class 'ImageAnnotatorClient' not found
Which is this line :
$imageAnnotator = new ImageAnnotatorClient([
What could possible cause the error ? From the construct above i already include or require_once the Path to the Class.
Is there something that i have missed in here ?
Thank You

This is the answer.
Check this post : Namespace in PHP CodeIgniter Framework
Just add the code to detect the namespace in the bottom of the config.php

Related

Uploading a file to a custom path in codeigniter

I'm trying to upload a file but I keep getting a "The upload path does not appear to be valid." error. The problem is the path I'm trying to upload to is in the directory just outside the current one. The current folder structure is as follows:
application
assets
- uploads
- profile_pictures
Admin
- application
- assets
I am attempting to upload a picture from the admin application into the 'assets/uploads/profile_pictures' folder which is in the main application root directory. The only issue is correcting the path.
Here's the code from the Controller:
public function update_image(){
$user_id= $this->input->post('user_id');
//$user_id=$this->input->post('user_id');
$query5 = $this->db->get_where('user_details', array('user_id' => $user_id));
$name_user = $query5->row()->name;
$name='profile_image_edit';
$user_img=$this->function->upload_profile_images(array($name), $name_user);
var_dump($user_img);
$this->db->set("image_path",$user_img);
$this->db->where("user_id",$user_id);
$update = $this->db->update("users");
if($update)
{
echo 'Profile Image Updated.';
}
else
{
echo 'Profile Image Update Failed.';
}
}
And here's the code from the Model:
public function upload_profile_images($names, $username)
{
$config['upload_path']='./assets/uploads/profile_pictures';
$config['allowed_types']='jpeg|jpg|png';
$path = $_FILES[$names[0]]['name'];
var_dump($names[0]);
var_dump($path);
$ste_d =date('YmdHis') . gettimeofday()['usec'];
$newName = str_replace("",'',str_replace("",'',"$ste_d.str_replace(" ",'_',str_replace(".","",pathinfo($path, PATHINFO_FILENAME)))."_muddy.")).pathinfo($path, PATHINFO_EXTENSION);
$config['file_name'] = $username ."_". $newName;
$this->upload->initialize($config);
$this->load->library('upload', $config['upload_path']);
$check = true;
for($i = 0; $i < count($names) && $check; $i++)
{
if ( ! $this->upload->do_upload($names[$i]))
{
$path='./assets/uploads/profile_pictures';
$this->load->helper("file");
$error = array('error' => $this->upload->display_errors());
var_dump($error);
// delete_files($path, true);
$check = false;
return false;
}
else
{
$data = array('upload_data' => $this->upload->data());
$check = true;
return 'assets/uploads/profile_pictures'.'/'.$data['upload_data']['file_name'];
}
}
}
How do I set a custom path so the file is always saved in the desired directory of assets/uploads/profile_pictures from the Admin application. Thanks for any help!

Upload File from Rest client to codeigniter

I know it could be a duplicate but i need a bit more help in that.
I have started working on making api for an android application in codeigniter. And currently working on making api for uploading an image.. I am using https://github.com/chriskacerguis/codeigniter-restserver
using postman to upload images to test my API but
but i am getting something like
'------WebKitFormBoundaryXkKFa0QV2XVs0EoK
Content-Disposition:_form-data;_name' => string '"filesss"; filename="17264394_1739947152983817_1705887364349350305_n.jpg"
Content-Type: image/jpeg
�����JFIF����������Photoshop 3.0�8BIM������g�Vnlfejt43YHm4REx3e4k(�bFBMD01000abe0300002f19000082320000643300004b3400002f4d0000c46f0000d3750000b8780000b07b000096cd0000��ICC_PROFILE���lcms��mntrRGB XYZ
Now can any one help me how to be able to save the image on my server
below is my code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH . './libraries/REST_Controller.php';
use Restserver\Libraries\REST_Controller;
class Update_image extends REST_Controller{
function __construct(){
parent::__construct();
$models[] = 'Quiz_model';
$models[] = 'Users_model';
$this->load->model($models);
$libs[] = 'form_validation';
$libs[] = 'image_lib';
$libs[] = 'email';
//$libs[] = 'rest';
$this->load->library($libs);
$helpers[] = 'file';
$helpers[] = 'security';
$helpers[] = 'url';
$helpers[] = 'string';
$this->load->helper($helpers);
}
function index_post(){
$users_id = $this->input->post('users_id');
$users_id = 6;
$config['upload_path'] = './public/user_images/';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = ; // for 5mb file
$config['max_width'] = 5000;
$config['max_height'] = 5000;
$this->load->library('upload', $config);
if(!$this->upload->do_upload('users_image')){
$error = array('error' => $this->upload->display_errors('<span>','<span>'));
$data['msg'] = error('Please Fix the errors below');
$data['file_upload_error'] = formErrorParse($this->upload->display_errors());
$this->form_validation->set_message('quiz_image', implode('<br/>', $error));
$response['status'] = 0;
$response['msg'] = strip_tags($this->upload->display_errors());
}else{
$uploadStat = $this->upload->data();
$img_config['image_library'] = 'gd2';
$img_config['source_image'] = './public/uploads/user_images/'.$uploadStat['file_name'];
$img_config['new_image'] = './public/uploads/user_images/thumbnail/'.$uploadStat['file_name'];
//$img_config['create_thumb'] = TRUE;
$img_config['maintain_ratio'] = TRUE;
$img_config['width'] = 150;
$img_config['height'] = 150;
$this->image_lib->clear();
$this->image_lib->initialize($img_config);
$this->image_lib->resize();
$updates['users_images'] = $uploadStat['file_name'];
$cond['users_id'] = $users_id;
$this->db->update('users', $updates, $cond);
$response['status'] = 1;
$response['msg'] = 'Image Uploaded';
}
$this->response($response, 200);
}
}
I had exactly same problem as you.
But solved after removing Content-Type from headers in postman.
Then you'll get data in $_FILES.
Make sure your php version is 5.6 or above,i had the same problem and solved it by switching to php version 7.

memory limit and slow upload using class upload php

i am creating upload image using class upload from https://www.verot.net/
my problem: output image 2 (real photo and edit-resize photo).
all work but it wasting time while processing upload.
and when i check size real photo before and after upload, size not same.
$counter=1;
foreach ($files as $file) {
$handle = new Upload($file);
if ($handle->uploaded)
{
$handle->Process("real");
$handle->dir_chmod = 0777;
//$handle->jpeg_quality = 85;
//jenis file yang diijinkan
$handle->allowed = array('image/*');//VALIDASI UPLOAD GAMBAR
//$handle->image_resize = false;
/*----first-START----*/
if ($handle->processed) {
${'pathPhotoReal'.$counter} = 'real/'.$handle->file_dst_name;
echo ${'pathPhotoReal'.$counter}."<br>";
${'namaFoto'.$counter} = $_POST['text'.$counter];
echo ${'namaFoto'.$counter}."<br>";
}
else {
// one error occured
echo ' Error: ' . $handle->error . '';
}
/*----first-FINISH----*/
// we now process the image a second time, with some other settings
//$handle->allowed = array('image/*');
$handle->image_ratio = true;
$handle->image_ratio_fill = true;
$handle->image_resize = true;
$handle->image_x = 300;
$handle->image_y = 300;
$handle->Process('edit');
/*----second-START----*/
if ($handle->processed) {
${'pathFotoEdit'.$counter} = 'edit/'.$handle->file_dst_name;
echo ${'pathFotoEdit'.$counter}."<br>";
}
else {
// one error occured
echo ' Error: ' . $handle->error . '';
}
/*----second-FINISH----*/
$counter = $counter + 1;
//$handle->clean();
else {
// if we're here, the upload file failed for some reasons
// i.e. the server didn't receive the file
echo ' File not upload ' . $handle->error . '';
echo($handle->log);
}
}
in my last code using else{echo ' File not upload ' . $handle->error . '';}
it always show, inside folder pathPhoto have saved photo inside. i think upload success.
try changing the folder permissions from filezilla.
With this you can know if the server allows you to make those persmisos

Verot class.upload.php uploading big files

I use an upload form to upload images. Small image like < 4mb will work.
But if I upload an image with a file size like 5.7MB, it doesn't do anything. It just doesn't upload the file. I have searched a lot but I couldn't figure it out. I think the problem has to deal with this code:
case 'png':
if (!function_exists('imagecreatefrompng')) {
$this->processed = false;
$this->error = $this->translate('no_create_support', array('PNG'));
} else {
echo $this->file_src_pathname;
echo $this->log;
echo $this->error;
echo $image_src = #imagecreatefrompng($this->file_src_pathname);
if (!$image_src) {
$this->processed = false;
$this->error = $this->translate('create_error', array('PNG'));
} else {
$this->log .= '- source image is PNG<br />';
}
}
break;
The #imagecreatefrompng($this->file_src_pathname) function is that piece of code where my code breaks. It doesn't output anything after that code, except when I comment it out. I have already changed my memory limit to 256M and the file upload to 64M. The file name is set. I have no idea why it only breaks my code when it has to deal with big files. Do any of you guys have an idea?
The code on the file upload page is:
//form processing
include('../includes/class.upload.php');
$files = array();
foreach ($_FILES['my_field'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
if(!empty($file)){
$handle = new Upload($file, 'nl_NL');
if (!file_exists("../classified_images/$adid"))
mkdir("../classified_images/$adid", 0777);
$tag_code_p = generatePassword(25);
if ($handle->uploaded) {
$oriname = $handle->file_src_name;
$handle->mime_magic_check = true;
$handle->allowed = array('image/*');
$handle->image_convert = 'jpg';
$newname = $adid."_big_".$tag_code_p;
$handle->file_new_name_body = $newname;
$handle->image_resize = true;
$handle->image_ratio_fill = true;
$handle->image_y = 600;
$handle->image_x = 800;
$handle->image_background_color = '#FFFFFF';
// // now, we start the upload 'process'. That is, to copy the uploaded file
// // from its temporary location to the wanted location
// // It could be something like $handle->Process('/home/www/my_uploads/');
$handle->Process("../classified_images/");
// we check if everything went OK
if ($handle->processed) {
$handle->image_convert = 'jpg';
$newnamesmall =$adid."_small_".$tag_code_p;
$handle->file_new_name_body = $newnamesmall;
$handle->image_resize = true;
$handle->image_ratio_fill = true;
$handle->image_y = 94;
$handle->image_x = 125;
$handle->image_background_color = '#FFFFFF';
// now, we start the upload 'process'. That is, to copy the uploaded file
// from its temporary location to the wanted location
// It could be something like $handle->Process('/home/www/my_uploads/');
$handle->Process("../classified_images/");
$handle->clean();
//inserten in database
$sql_foto_insert = "insert into photos
( adid, photosmall, photo)
values
('$adid', '$newnamesmall.jpg','$newname.jpg')";
$foto_result = mysql_query($sql_foto_insert);
// everything was fine !
//$msg .= $oriname.' '.LANG_FOTOS_SAVED.'<br />';
$allok = 1;
} else {
// one error occured
$msg .= $handle->error . '<br />';
}
}
This can be caused by configuration issues. Since this happens for files > certain size, I feel it can be related to php ini settings.
Check upload_max_filesize and post_max_size in your php ini settings. These could be set to 4MB. You can increase these values to make it work.
If you are in a shared hosting environment where you cannot edit php ini, you can add them to .htaccess file like so:
php_value upload_max_filesize 7M
php_value post_max_size 7M
Also you should remove the # from your function to see what the error is. Suppressing errors by adding # is a bad idea while developing/debugging.
Additionally, if you are in a local machine or own dev server, open the apache error_log and check the last few lines to see what the error is. If you are on a third party server, most control panels provide an interface to view the error log.

Codeigniter Multiple File Upload Encryption Issue

I've got a big form that allows users to upload multiple files/filetypes to an offer/bid they are creating. Everything is working fine except one piece: the name encryption of the files before saving to the database.
I haven't found a rhyme or reason for it, but it's hit or miss. The image works fine every time. The other documents (which allow all [*] types, but primarily will consist of various business docs such as pdf, doc, xls, etc.) are the ones that are spotty.
I found threads on SO and elsewhere about general issues with the name encryption but have yet to come across one that deals with the specificity of my issue.
Here's the upload function:
//for multi uploads
function do_uploads($name, $file)
{
$status ="";
$msg = "";
$file_element_name = $name;
//go through and figure out where it goes
if($name == "QuoteDoc") {
$folder = "quotedocs";
$allowed = '*';
}
else if($name == "ProductOfferPhoto") {
$folder = "product_photos";
$allowed = 'jpeg|jpg|png|gif';
}
else if($name == "ResearchWhtPaper1" || $name == "ResearchWhtPaper2") {
$folder = "research";
$allowed = "*";
}
else if($name == "ProductLiterature1" || $name == "ProductLiterature2") {
$folder = "literature";
$allowed = "*";
}
else if ($name == "FDALink") {
$folder = "fda";
$allowed = "*";
}
$config['upload_path'] = './uploads/' . $folder;
$config['allowed_types'] = $allowed;
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else {
$data = $this->upload->data();
}
#unlink($_FILES[$file_element_name]);
//what's up?
//return $this->upload->data();
return array('status' => $status, 'msg' => $msg, 'data' => $this->upload->data(), 'allowed'=>$allowed);
}
Any help would be greatly appreciated.
You're not stating your question very clearly:
Are the names simply not being encrypted, but still uploading to the correct directories?
Are you setting these inside a loop, where perhaps the class instance is not being re-initialized? Does the first file encrypt correctly, but not the subsequent ones?
Can you track which file types are not working correctly?
I have trouble believing it is completely "random", and think there's just not enough research being done here
Solution from below:
You need to use $this->upload->initialize($config) to change the config, as the library will only be loaded once

Categories