imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file - laravel-4

I'm using intervention/image module with laravel 4.2 , to upload images i'm using this code :
if (Input::hasFile('image'))
{
$file = Input::file('image');
$file->move('uploads/2/', $file->getClientOriginalName());
$image = Image::make(sprintf('uploads/2/%s', $file->getClientOriginalName()))->resize(120, 120)->save();
return 'yes';
}
With some images it works , with some images it produces this error :
imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file
switch ($info[2]) {
case IMAGETYPE_PNG:
$core = imagecreatefrompng($path);
$this->gdResourceToTruecolor($core);
break;
case IMAGETYPE_JPEG:
$core = imagecreatefromjpeg($path);
$this->gdResourceToTruecolor($core);
break;

This is because you upload corrupted images and GD can't handle that kind of images. Please check it in this issue .
Try to suppress this error like this.
ini_set('gd.jpeg_ignore_warning', true);
Hope it will be useful for you.

Related

Using imagejpeg() in Laravel

I am migrating my existing PHP program to Laravel. I know the upload should be $request->files->store('images'); but this doesn't compress the images beforehand.
I have found Intervention Image plugin for Laravel but I don't want to use it because I want it to be pure PHP only.
My working code from pure PHP was:
$info = getimagesize($tmpFilename);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($tmpFilename);
} else if ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($tmpFilename);
} else if ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($tmpFilename);
}
imagejpeg($image, $path, 60);
I know the images get saved at /storage/app/public/ so I used that path for imagejpeg as well. This is my laravel code:
$tmp_file = $inner->getPathName();
imagejpeg($tmp_file, '/storage/app/public/images/hehe.jpg', 60);
But it doesn't work. It only says
imagejpeg(/storage/app/public/images/hehe.jpg): failed to open stream: No such file or directory
Any help would be appreciated

Displaying a BLOB file(An Image) gotten from a guzzle request

I was successfully able to get an image(which is stored as a BLOB file) from an API endpoint in guzzle, but I am having issues displaying this BLOB file as an image
I have tried several PHP functions for manipulating and converting a BLOB file to an image but all has been abortive.
after sending the request to my guzzle trait, I decided to var_dump the result to be sure that it was successful
$userid = $_COOKIE['id'];
$url = 'users/image/'.$userid;
$requestResult = $this->sendGetWithHeader('users/image/'.$userid);
$result = $requestResult->getBody()->read(1024);
//$res = file_get_contents($result);
// fopen($result, 0);
var_dump($result);
echo "<hr>";
var_dump($requestResult);
// $code = $requestResult->getStatusCode();
// var_dump($code);
My expected result is an image file but the actual is still the raw BLOB file gotten from my Guzzle request
string(1024) "����JFIF���        ��V�"��6 ���UG_ks1��r�[�% ��JMd�CL,��8�Q�B�yoA��g�p�-�a�f� D �)8#�.)ɠ� �yea#4��ԃ(��t��Ew��մPV'J��R��u������Ju��U ��ԥ��zѩaė��ya$�2�C�Sa�R$�4� ���� 2t��$��L�D���R�$�ґ-&RVdm��IDq)Jc�"'9�;/ �sb{��Z�r�̮��Q_MR=5�Gt���ddA�6�Fa�L���JGi�kh�d�FA�%(�$� �����.�� H�)��-BL������h|#���WW)݋r�"V[V2˚:��j��˩�>��-$��I�Y�#%dRL(K�(�-�m�I�t��R�JV#�I&JR��0����O2��d�-e#5�2}�2�D'��,Bע��{��!�k�Uw�2ʶ�]cAD�WPw���$��!�Ғu�X!��(�D%I0i�����Lye XI9) �[Nc����#!�miY,Rkiq(���$����mƬ��y��a����崔͒�t7"����͌ΊJgk Q��Ah�Iq$���ʍA�FmJ���7��AJ�a/�rB�"02A����#�d��J%D� �P�yH���m\ż>�i$��I�(�3jm�542k,��t#��#��#D�F�TJDP" �Z(��7�IZ���h9)$��$�Ԣ�Y� m�D�I�֐4�����Da�%DX�o ���fhh�.�c��aQhcΉ�٠��)��"
Save your blob response to a file as follows
$stream = \GuzzleHttp\Psr7\Utils::streamFor($requestResult->getBody());
file_put_contents('path/to/file.extension',$stream->getContents())
See Convert blog image to file
Look at this example - https://github.com/andriichuk/php-curl-cookbook#download-file
Use 'sink' option to save file from request:
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
$imageFilePath = __DIR__ . '/resource/image.jpeg';
$imageFileResource = fopen($imageFilePath, 'w+');
$httpClient = new Client();
$response = $httpClient->get(
'https://httpbin.org/image/jpeg',
[
RequestOptions::SINK => $imageFileResource,
]
);
if ($response->getStatusCode() === 200) {
echo 'The image has been successfully downloaded: ' . $imageFilePath;
}

Laravel 5.4 Storage : downloading files. File does not exist, but clearly it does

I have been going round and round with this. I have uploads working with the follow:
public function store(Tool $tool)
{
If(Input::hasFile('file')){
$file = Input::file('file');
$name = $file->getClientOriginalName();
$path=Storage::put('public',$file); //Storage::disk('local')->put($name,$file,'public');
$file = new File;
$file->tool_id = $tool->id;
$file->file_name = $name;
$file->path_to_file = $path;
$file->name_on_disk = basename($path);
$file->user_name = \Auth::user()->name;
$file->save();
return back();
}
however when I try to download with:
public function show($filename)
{
$url = Storage::disk('public')->url($filename);
///$file = Storage::disk('public')->get($filename);
return response()->download($url);
}
I get the FileNotFound exception from laravel
However, if I use this instead:
$file = Storage::disk('public')->get($filename);
return response()->download($file);
I get
FileNotFoundException in File.php line 37: The file "use calib;
insert into
notes(tool_id,user_id,note,created_at,updated_at)
VALUES(1,1,'windows server 2008 sucks',now(),now());" does not exist
which is the actual content of the file...
It can obviously find the file. but why wont it download?
Try this:
return response()->download(storage_path("app/public/{$filename}"));
Replace:
$file = Storage::disk('public')->get($filename);
return response()->download($file);
With:
return response()->download(storage_path('app/public/' . $filename));
response()->download() takes a path to a file, not a file content. More information here: https://laravel.com/docs/5.4/responses#file-downloads
If any one still could not find their file even though the file clearly exists then try
return response()->file(storage_path('/app/' . $filename, $headers));
It could be due to a missing directory separator or it isn't stored inside the public folder.

Laravel, Intervention, Corrupt JPEG data: 1130 extraneous bytes before marker 0xd9

so i give up. i have more forum windows open than i can count, have tried a bunch of different things and still no luck. i have installed intervention with laravel 5.0 and can get some images through but others (many) bomb out with the following error
ErrorException in Decoder.php line 35:
imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Corrupt JPEG data: 1130 extraneous bytes before marker 0xd9
use Intervention\Image\ImageManager;
//use Intervention\Image\Image;
//use Intervention\Image\Facades\Image;
use Image;
public function storepic($id)
{
$gallry=auth()->user()->galleries()->findorfail($id);
$files = Input::file('images');
// Making counting of uploaded images
$file_count = count($files);
// start count how many uploaded
$uploadcount = 0;
ini_set('gd.jpeg_ignore_warning', true);
$dt=Carbon::now();
Carbon::setToStringFormat('omj_His');
foreach($files as $file) {
$rules = array('file' =>'required|mimes:png,gif,jpeg,jpg');
$d=array('file'=> $file);
$ext=$file->getClientOriginalExtension();
$mim=$file->getClientMimeType();
$validator = Validator::make($d, $rules);
if($validator->passes()){
//save file
$upPath = 'uploads/galleries/' . $id . '/';
$filename = $dt . $file->getClientOriginalName() ;
$upload_success = $file->move($upPath, $filename);
// save to db
$imag['oFileName']=$file->getClientOriginalName() ;
$imag['sFileName']=$filename;
$imag['gid']=$id;
$pic=new Pictures($imag);
$pic->save();
if ($gallry['img_id']==null){
$gallry['img_id']=$pic['pid'];
$gallry->save();
}
//create thumbnail
$path = 'uploads/thumbs/' . $id . '/';
// below used to all be one statement - it didn't effect it either way
$img= Image::make($upPath . $filename);
$img->resize(null, 100, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($path . $filename);
$uploadcount ++;
}
}
so i've tried to
1. suppress the errors with
ini_set('gd.jpeg_ignore_warning', true);
in multiple places
2. recreate image with binary, which blew the image to 5x in size
3. tried createimagefromstring as opposed to jpeg
i'm thinking/wondering
-if i'm not suppressing errors correctly.
-is the problem with the gd library as opposed to imagick. i haven't added imagick yet, but can, it just seems like a pain
-i could try to do the resize in another procedure, but that just seems to be putting off the problem
any thoughts would be appreciated. thanks for your help!
I had the same well known problem. Adding the ini_set as the first line of the index.php didn't work in my case.
I ended up with a try catch solution, warning the user the JPG is damaged.
try {
$img = Image::make($filename);
} catch(\Exception $e) {
my_flash_message($e->message);
}
Take care Exception is namespaced so you have to use the slash.
Hope it helps.

Getting Error in Library inclusion in Codeigniter controller

When i run my aaplication in external server i get eror ,
Message: Login::include_once(application/third_party/mpdf/mpdf.php) [function.Login-include-once]: failed to open stream: No such file or directory.
The same application was running perfect in local server. Can anyone please suggest what could be wrong with it. My controller function ,
function pdfapp() //for test run individually
{
$this->load->model('Registration_model');
$appno='4/SCSELB/2013/KL01';
$data['table'] = $this->Registration_model->getall_app($appno);
$data['own_land'] = $this->Registration_model->get_ownland($appno);
$data['loan_data'] = $this->Registration_model->getloan_data($appno);
$apppdf='4_SCSELB_2013_KL01';
$data['apppdf']=$apppdf;
$pdfFilePath = FCPATH."reports/application/$apppdf.pdf";
if (file_exists($pdfFilePath) == FALSE)
{
ini_set('memory_limit','32M');
$html = $this->load->view('pdf_report2', $data, true);
include_once APPPATH.'third_party/mpdf/mpdf.php';
$mpdf=new mPDF('c');
$mpdf->SetFooter(' copyright# KSDC'.'|{PAGENO}|'.'Applied on '.date('d-M-Y H.i.s'));
$mpdf->WriteHTML($html);
$mpdf->Output($pdfFilePath, 'F');
}
$this->load->view('pdf_report2',$data);
}
The error you're getting is of a file not existing, Did you you debug this line ?
APPPATH.'third_party/mpdf/mpdf.php'; ?
what path do you get if you var_dump it?

Resources