Pages

Thursday, February 24, 2011

PHP GD Lib image generation from jpg file

<?php

function getCenterX($font_size, $font_file, $text, $img_width) {
  $box = imagettfbbox($font_size, 0, $font_file, $text);
  $text_width = $box[2] - $box[0];
// Position to align in center
  $position_center = ceil(($img_width - $text_width) / 2);
  return($position_center);
}

$img_width = 960;
$img_height = 640;
$font_file = 'Kentucky.ttf';
$canvas = imagecreatefromjpeg('coupan_ip4.jpg');
$pre_header = '&lt;b&gt;sare jahan se achcha hindusit';
$main_header = 'Jan gan man';
$main_description = "Main Description";
$sub_description = "Main Description";
$ccode = "Coupon Code : 112345767";
$expire = "Expires: 02/09/2011";
$ccode_server ="Server: select coupon code 18";
$disclaimer = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr,  sed diam nonumy eirmod tempor invidunt ut labore et ";

// Allocate colors
$pink = imagecolorallocate($canvas, 255, 105, 180);
$white = imagecolorallocate($canvas, 255, 255, 255);
$green = imagecolorallocate($canvas, 37, 102, 70);
$black = imagecolorallocate($canvas, 0, 0, 0);
$red = imagecolorallocate($canvas, 190, 33, 50);

imagettftext ($canvas, 20, 0, getCenterX(20, $font_file, $pre_header, $img_width), 40, $black, $font_file, $pre_header);
imagettftext ($canvas, 40, 0, getCenterX(40, $font_file, $main_header, $img_width), 100, $red, $font_file, $main_header);
imagettftext ($canvas, 18, 0, 10, 140, $green, $font_file, $main_description);
imagettftext ($canvas, 13, 0, 10, 180, $black, $font_file, $sub_description);
imagettftext ($canvas, 16, 0, 10, 200, $black, $font_file, $ccode);
imagettftext ($canvas, 13, 0, 10, 220, $black, $font_file, $expire);
imagettftext ($canvas, 13, 0, 10, 240, $black, $font_file, $ccode_server);
imagettftext ($canvas, 13, 0, 10, ($img_height-50), $black, $font_file, $disclaimer);


//echo $font_width = ImageFontWidthByFilename($font_file);
// Output and free from memory
header('Content-Type: image/jpg');

imagejpeg($canvas);
imagedestroy($canvas);
?>