Philipp Klemeshov
Philipp Klemeshov

Reputation: 413

How not to output an image to the browser?

My code:

ob_start();
imagejpeg($resource, NULL, 75);  break; // best quality
$resource = ob_get_contents();
ob_end_flush();

I use imagejpeg() only for output buffering, I dont need to output to browser. Any ideas?

Upvotes: 3

Views: 615

Answers (2)

Marc
Marc

Reputation: 3709

Let's try to analyse what you did there:

// start output buffering
ob_start();
// output the image - since ob is on: buffer it
imagejpeg($resource, NULL, 75);
// this break could be a problem - if this is in a control structure, remove it
break;
// save the ob in $resouce
$resource = ob_get_contents();

// here is the image now in $resource AND in the output buffer since you didn't clean it (the ob)

// end ob and flush (= send the ob)
ob_end_flush();

So what you did wrong is, that you 1) didn't clean the outputbuffer and/or 2) flushed the ob.

My recommendation would be to use ob_get_clean (reference) (simple example):

$im = imagecreatetruecolor(120, 20);
ob_start();
imagejpeg($im);
$var = ob_get_clean();

Upvotes: 2

Richard
Richard

Reputation: 2815

You break the process, if it is in a loop. So the OB will not be closed and the output is at the end of the parsing process. Also, you do not have to flush but to clean. Use:

ob_start();
imagejpeg($resource, NULL, 75); // best quality
$resource = ob_get_contents();
ob_end_clean();
break;

Or:

ob_start();
imagejpeg($resource, NULL, 75); // best quality
$resource = ob_get_contents();
ob_clean();
// Some other code
ob_end_flush(); // Output the rest
break;

Upvotes: 0

Related Questions