Muhammad Ali
Muhammad Ali

Reputation: 339

php header('Content-type: image/jpeg') shows borken image

I am trying to use an email address as an image.

I wrote the following code:

<?php 

header('Content-type: image/jpeg');

echo $email= '[email protected]';
echo $email_length= strlen($email);
echo $font_size= 4;

echo $image_height= imagefontheight($font_size);
echo $image_width= imagefontwidth($font_size) * $email_length;

$image= imagecreate($image_width, $image_height);

imagecolorallocate($image, 255, 255, 255);

$font_color= imagecolorallocate($image, 0, 0, 0);

imagestring($image, $font_size, 0, 0, $email, $font_color);

imagejpeg($image);

?>

I googled out and tried following solutions.

  1. Gd p library is configured and working.

  2. I cleared the browser cache.

  3. I have check all function on php manual.

Please Note: I also get broken image when I only the following code:

header('Content-type: image/jpeg');

My gd configuration:

GD Support enabled GD Version bundled (2.1.0 compatible) FreeType Support enabled FreeType Linkage with freetype FreeType Version 2.4.10 GIF Read Support enabled GIF Create Support enabled JPEG Support enabled libJPEG Version unknown PNG Support enabled libPNG Version 1.5.14 WBMP Support enabled XPM Support enabled libXpm Version 30411 XBM Support enabled WebP Support enabled

I appreciate your efforts. Thanks

Upvotes: 0

Views: 486

Answers (2)

Shailesh Katarmal
Shailesh Katarmal

Reputation: 2785

Remove echo keyword and try it.

$email= '[email protected]';
$email_length= strlen($email);
$font_size= 4;

$image_height= imagefontheight($font_size);
$image_width= imagefontwidth($font_size) * $email_length;

$image= imagecreate($image_width, $image_height);

imagecolorallocate($image, 255, 255, 255);

$font_color= imagecolorallocate($image, 0, 0, 0);

imagestring($image, $font_size, 0, 0, $email, $font_color);

header('Content-type: image/jpeg');

imagejpeg($image);
imagedestroy($image);

Upvotes: 0

semihcosu
semihcosu

Reputation: 346

As @Ultimaer mentioned, you should remove all your echoes. Your code is putting some information on top of your image data, that is probably why it looks broken.

Here's the working source:

<?php
header('Content-type: image/jpeg');

$email= '[email protected]';
$email_length= strlen($email);
$font_size= 4;

$image_height= imagefontheight($font_size);
$image_width= imagefontwidth($font_size) * $email_length;

$image= imagecreate($image_width, $image_height);

imagecolorallocate($image, 255, 255, 255);

$font_color= imagecolorallocate($image, 0, 0, 0);

imagestring($image, $font_size, 0, 0, $email, $font_color);

imagejpeg($image);

Upvotes: 1

Related Questions