如何使用PHP制作jpeg格式的图像?

Here is my current code:

.
.
.

ob_start (); 
imagepng($im, null, 9, PNG_ALL_FILTERS);
$image_data = ob_get_contents (); 
ob_end_clean (); 
echo "<img src='data:image/png;base64," . base64_encode ($image_data) . "' />";

The output is a .png image which looks right. Now I want to make it this way:

.
.
.

header('Content-Type: image/jpeg');
imagejpeg($im);
imagedestroy($im);

But in this case, the image won't be created. The result will be a black page:

enter image description here

Any idea what's the problem and how can I fix it?