return dynamic image zf2 - image

I use zend framework 2 and try to return an created with gd2 library jpeg image . but it doesn't work. could you look my code what's the problem? My code is run with plain php in normally but in zf2 problem?
class PictureController extends AbstractActionController
{
public function colorPaletteAction(){
....
....
//canvas created at above.
imagejpeg($canvas);
imagedestroy($canvas);
$response = $this->getResponse();
return $response->getHeaders()->addHeaderLine('Content-Type', 'image/jpeg');
}
}

imagejpeg outputs the data immediately which you don't want to do. You can either use the output buffer to capture this data or write it to a file first. The output buffer is probably easiest:
public function colorPaletteAction()
{
// [create $canvas]
ob_start();
imagejpeg($canvas);
$imageData = ob_get_contents();
ob_end_clean();
imagedestroy($canvas);
$response = $this->getResponse();
$response->getHeaders()->addHeaderLine('Content-Type', 'image/jpeg');
$response->setContent($imageData);
return $response;
}
If this doesn't work, temporarily comment out the Content-Type header line to see what output you're getting. Make sure there aren't any errors or HTML in the output.

You set the Content-Type header to 'image/png' instead of 'image/jpeg'.
Also try adding the content-transfer-encoding and content-length headers:
$response->getHeaders()->addHeaderLine('Content-Transfer-Encoding', 'binary')
->addHeaderLine('Content-Length', mb_strlen($yourJpegContent));
I also don't see you adding the actual content to the response:
$response->setContent($yourJpegContent);
where $yourJpegContent contains the binary image data.

Related

Method Illuminate\View\View::header does not exist

I'm trying to produce a js file to let other webmasters use my news headlines in their websites:
Route::get('/script/news/{slug}/{count}.js',function($slug,$count) {
return view('webmaster_script')->
with(compact("slug","count"))->
header('Content-Type', 'application/javascript');
});
But it says
BadMethodCallException Method Illuminate\View\View::header does not
exist
How can I fix it?
Script content is generated successfully . I just want to change the MIME type.
Thanks in advance
Laravel's documentation gives following example
If you need control over the response's status and headers but also need to return a view as the response's content, you should use the view method:
return response()
->view('hello', $data, 200)
->header('Content-Type', $type);
So following should work:
return response()
->view('webmaster_script', compact("slug", "count"))
->header('Content-Type', 'application/javascript');

return file response in laravel not working

I'm using laravel 5.2 , I've used response()->file() function to return file. On localhost it is working as expected but on live server file is being downloaded automatically (with no extension). But i wish to open it instead of downlod. Anyone can help?
Here is my code:
public function returnFile($slug)
{$file = Mixes::where('id_name,'=',$slug)->get()->first();
return response()->file('./path/to/file/'.$file->name);}
Thanks.
You'll need to add header to your response.
Response with header example:
$response->header('Content-Type', 'application/pdf');
Simple example:
$file = File::get($file);
$response = Response::make($file, 200);
$response->header('Content-Type', 'application/pdf');
return $response;
Then the file will display in your browser window.
This solution will work with files pdf,docx,doc,xls.
Hope it will help!

Ask, how to use redirect without contition?

i have codes like this
function download(){
$id = $this->uri->segment(3);
$dat = $this->mikland->gidiklanfoto($id);
foreach ($dat as $item){
$name = $item->foto;
$data = file_get_contents(base_url()."/uploads/".$name); // filenya
force_download($name,$data);
}
redirect('cikland/viewiklan/'.$id);
}
when the function are running, redirect cannot run.,
somebody can help??
i think is a simple thing but i dont know the trick., thank's before
At the end of force_download() there is an exit() statement, so no code after a forced download will run.
And you are trying to have several files downloaded at the same time - using some sort of multipart mime type, that might or might not work, but not in the given case, because CI's force_download() does not seem to support that.
An alternative to that would be creating a temporary archive file which contains all the files for download; please have a look at the official documentation on compression and archives for that.
If you'd want to send a redirection header along with the file, you'd have to do it like this:
function download(){
// add this somewhere befor the download
header('Location: '.site_url('cikland/viewiklan/'.$id));
$id = $this->uri->segment(3);
$dat = $this->mikland->gidiklanfoto($id);
// only first item is downloaded
foreach ($dat as $item)
{
$name = $item->foto;
$data = file_get_contents(base_url()."/uploads/".$name); // filenya
force_download($name,$data);
}
}
But the question would remain how the browsers would deal with a redirect and content: most likely you would only get the redirect.
You need load url helper.
$this->load->helper('url');
after
redirect("cikland/viewiklan/$id", 'refresh');
or
redirect("cikland/viewiklan/$id", 'location', 301);
Font: http://ellislab.com/codeigniter%20/user-guide/helpers/url_helper.html
redirect() method redirects to a URL. You need to pass it a full URL (as it uses the header() function which according to the RFC for HTTP1.1 requires a full URL.
so you need to hard code the full url like the given example - redirect('http://www.yoursite.com/cikland/viewiklan/'.$id);

PHPWord class in CodeIgniter is not generating correct, throwing errors in word file

Ok, so I'm having difficulty with the PHPWord class which can be found: http://phpword.codeplex.com
The weird thing about it is when I use this same code in the "example" file it works fine in generating. When I don't force a download using headers the file will open up just fine. Using this code though with the headers is causing it when it downloads to throw errors in the word file saying the file is corrupt and can't be opened, but then it opens up just fine.
public function export()
{
// Load PHPWORD Library
$this->load->library('PHPWord');
$sec = $this->phpword->createSection($secStyle);
$header = $sec->createHeader();
$header->addWatermark('images/CC_watermark.png', array('marginTop'=>1015, 'marginLeft'=>-80));
$resultSelected = $this->input->post('cbox');
foreach($resultSelected as $row)
{
$sec->addText($row);
echo $row."<br>";
}
$fileName = "Plan_Generate_".date('Ymd').".docx";
// Force Download
$filePath = $fileName;
$fileName = basename($filePath);
// $fileSize = filesize($filePath);
// Output headers.
header("Cache-Control: private");
header("Content-Type: application/stream");
// header("Content-Length: ".$fileSize);
header("Content-Disposition: attachment; filename=".$fileName);
// Output file.
// readfile ($filePath);
// exit();
// Save File
// $fileName = "files/SomethingNew_".date("Ymd").".docx";
$objWriter = PHPWord_IOFactory::createWriter($this->phpword, 'Word2007');
$objWriter->save('php://output');
}
This is the code i'm using when trying to generate the file. The trouble I'm having is it's throwing an error when it tries to force download. Thanks for any help! Ask questions if you don't fully understand the question.
Update:
Here's the image of the error's I'm receiving. Thanks for the quick responses and I'm actually going to try the Codeigniters way of doing it Tomm. morning.
You should be setting headers via CodeIgniters functions, that is what could be causing the issue for you:
CI Output Class
$this->output->set_header();
Permits you to manually set server headers, which the output class will send for you when outputting the final rendered display. Example:
$this->output->set_header("HTTP/1.0 200 OK");
$this->output->set_header("HTTP/1.1 200 OK");
$this->output->set_header('Last-Modified: '.gmdate('D, d M Y H:i:s', $last_update).' GMT');
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate");
$this->output->set_header("Cache-Control: post-check=0, pre-check=0");
$this->output->set_header("Pragma: no-cache");
My assumption is you are trying to do update headers the PHP way, but you are playing by CI rules for output.
This was fixed by using CI's $this->download->force_download().
And by passing the data through ob_start(), ob_get_contents(), and ob_end_clean() for people needing help with it.
Are you sure you don't want
header("Content-Type: application/octet-stream");
instead of just stream? What is the actual error and is it word or the browser or php that is throwing the error?
Also, CodeIgniter has a download helper to send files... You may want to try that.
http://codeigniter.com/user_guide/helpers/download_helper.html

Is there a way to have a Codeigniter controller return an image?

I was wondering if there was a way for a controller to, instead of returning a string, or a view, return an image (be it JPG, PNG etc). For example, instead of ending with a $this->load->view('folder/special_view.php), I'd like to do something like $this->load->image('images/gorilla.png'), and have it so if my user were to go to that controller they would see an image as if they'd gone to a normal .png or jpeg. Can I set the headers so it expects a different MIME? Example code of this would be fantastic.
It would take forever for me to explain why I need this, but it involves bringing a premade CMS into codeigniter, and having it need certian things to be true. Thank you so much!
sure you can, use this instead of $this->load->view()
$filename="/path/to/file.jpg"; //<-- specify the image file
if(file_exists($filename)){
$mime = mime_content_type($filename); //<-- detect file type
header('Content-Length: '.filesize($filename)); //<-- sends filesize header
header("Content-Type: $mime"); //<-- send mime-type header
header('Content-Disposition: inline; filename="'.$filename.'";'); //<-- sends filename header
readfile($filename); //<--reads and outputs the file onto the output buffer
exit(); // or die()
}
This is not intended as One-upmanship, but pǝlɐɥʞ's suggestion is a pure PHP implementation that is not all that re-usable. You wanted to use the syntax $this->load->image('images/gorilla.png') so here is how you can.
Create /application/libraries/MY_Loader.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Loader Class
*
* Loads views and files
*
* #package CodeIgniter
* #subpackage Libraries
* #author Phil Sturgeon
* #category Loader
* #link http://codeigniter.com/user_guide/libraries/loader.html
*/
class MY_Loader extends CI_Loader {
function image($file_path, $mime_type_or_return = 'image/png')
{
$this->helper('file');
$image_content = read_file($file_path);
// Image was not found
if($image_content === FALSE)
{
show_error('Image "'.$file_path.'" could not be found.');
return FALSE;
}
// Return the image or output it?
if($mime_type_or_return === TRUE)
{
return $image_content;
}
header('Content-Length: '.strlen($image_content)); // sends filesize header
header('Content-Type: '.$mime_type_or_return); // send mime-type header
header('Content-Disposition: inline; filename="'.basename($file_path).'";'); // sends filename header
exit($image_content); // reads and outputs the file onto the output buffer
}
There are a few ways you can use this:
Basic output (default is jpeg)
$this->load->image('/path/to/images/gorilla.png');
Send mime-type to use other image types
$this->load->image('/path/to/images/gorilla.jpg', 'image/jpeg');
Return the image
$image = $this->load->image('/path/to/images/gorilla.php', TRUE);
Just like $this->load->view, the 3rd parameter being set to TRUE means it will return instead of directly outputting.
Hope this helps :-)
An easier way with automatic mime-type.
$this->load->helper('file');
$image_path = '/path/to/image/file';
$this->output->set_content_type(get_mime_by_extension($image_path));
$this->output->set_output(file_get_contents($image_path));
About the Phil's code:
In CodeIgniter 2.0, today, there are a one change that have to be made in order to make it work:
The library has to be in /application/core/MY_Loader.php
I like to remark a small typo about the library's explanation:
There is a mistake in the header "Basic output (default is jpeg)" because in fact the default is .png
Another solutions to the problem are:
I've made a small code to make it work with the core codeIgniter libraries:
$this->output->set_header("Content-Type: image/png");
$this->load->file('../images/example.png');
Or using the Image Manipulation Library
$config['image_library'] = "GD2";
$config['source_image'] = "../images/example.png";
$config['maintain_ratio'] = TRUE;
$config['dynamic_output'] = TRUE;
$this->load->library('image_lib', $config);
$image = $this->image_lib->resize();
In both cases you get the same image you get from the source but in the output.
But for me, I liked more the extension to the core library :-)
Thank you very much Phil.
This method works even if you have $config['compress_output'] set to TRUE
$filename="/path/to/file.jpg"; //<-- specify the image file
if(file_exists($filename)){
header('Content-Length: '.filesize($filename])); //<-- sends filesize header
header('Content-Type: image/jpg'); //<-- send mime-type header
header('Content-Disposition: inline; filename="'.$filename.'";'); //<-- sends filename header
$jpg = file_get_contents($filename);
$this->output->set_output($jpg);
}
If it fits your use case, simply redirecting to it is just fine. For example, tracking using images would be like:
// Do your logic here
redirect($image_path); // Or PHP's header location function
No need to change headers. Your use case may not fit this, but someone might find this useful ^_^
I would do a
$computedImage = 'path/to/the/image.ext';
$this->load->helper('file');
$this->output->set_content_type(get_mime_by_extension($computedImage))->set_output(file_get_contents($computedImage));
If this helps. Cheers!

Resources