GD Lib imagejpeg()无法输出图像

I am trying to generate an image using gd lib and load it into my html page using ajax.

In my php file I have a simple class which calls method to generate the image. I don't want to save the image to a directory.

Here's the method:

private function generate_image(){
    $im = imagecreatetruecolor(120, 20);
    $text_color = imagecolorallocate($im, 233, 14, 91);
    imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

    // Set the content type header - in this case image/jpeg
    header('Content-Type: image/jpeg');

    // Output the image
    imagejpeg($im);

    // Free up memory
    imagedestroy($im);
}

The result I am getting in my html page looks like this: ����JFIF��>CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), default quality ��C $.' ",#(7),01444'9=82<.342��C 2!!22222222222222222222222222222222222222222222222222��x"�� ���}!1AQa"q2 and so on.

Is it something to do with my placement of header('Content-Type: image/jpeg');? Should it not be in the method or class?