Wednesday, June 15, 2011

Membuat Banner dengan Ajax dan PHP menggunakan GD Library ( COPAS cipulaida.wordpress.com )

post kali ini saya akan mencoba membagi cara membuat image banner dengan title dan sub title seperti gambar dibawah ini menggunakan Ajax, dan PHP menggunakan GD library

OK langsung aja. Cara kerjanya :
  1. Upload gambar yang akan di jadikan banner menggunakan ajax di iframe
  2. Tambahkan Heading dan Subheading dengan javascript
  3. Buat Banner beserta Heading dan Subheading dengan PHP GD library

file : index.html => halaman depan dimana terdapat form untuk upload gambar (jpg/gif/png) dengan ajax yang di panggil melalui iframe yang akan digunakan untuk banner.
Setelah  upload berhasil akan muncul form untuk pengisian teks Heading dan Subheading.
01<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02<html xmlns="http://www.w3.org/1999/xhtml">
03<head>
04<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
05<title>Banner Creation Tool</title>
06 
07<style>
08.picture_preview {
09        position:relative;
10    float:left;
11    font-family:Arial, Helvetica, sans-serif;
12}
13.picture_preview .txt_heading_prev {
14    position:absolute;
15    font-size:25px; top:30px;
16    right:40px;
17}
18.picture_preview .txt_subheading_prev {
19    position:absolute;
20    font-size:15px; top:70px;
21    right:40px;
22}
23.msg {
24    background-color:#FFCcolor:#F00;
25}
26</style>
27<script src="js.js" language="javascript" type="text/javascript"></script>
28</head>
29<body>
30<iframe name="upload_iframe" id="upload_iframe" style="display:none;"></iframe>
31<form name="pictureForm" method="post" autocomplete="off" enctype="multipart/form-data">
32<table border="0">
33  <tr>
34    <td>Select Image</td>
35    <td>:</td>
36    <td><input type="file" name="picture" id="picture" onChange="return ajaxFileUpload(this);" /></td>
37  </tr>
38</form>
39<div id="msg"></div>
40<div id="txt_box" style="display:none">
41<table border="0">
42  <tr>
43    <td>Heading</td>
44    <td>:</td>
45    <td><input type="text" name="heading_txt" id="heading_txt" onkeyup="previewBanner()" /></td>
46  </tr>
47  <tr>
48    <td>SubHeading</td>
49    <td>:</td>
50    <td><input type="text" name="subheading_txt" id="subheading_txt" onkeyup="previewBanner()" /></td>
51  </tr>
52  <tr>
53    <td colspan="3" scope="row"><hr /></td>
54  </tr>
55  <tr>
56    <td><input type="button" value="Cancel" onclick="document.getElementById('msg').innerHTML = '<img src=images/loader-bar.gif />'; doAjaxCall('banner.php?do=cancel&img='+document.getElementById('picture').value+'&heading='+document.getElementById('heading_txt').value+'&subheading='+document.getElementById('subheading_txt').value+'&sid='+Math.random(), 'msg'); resetDisplay();" /></td>
57    <td>&nbsp;</td>
58    <td><input type="button" value="Submit" onclick="document.getElementById('msg').innerHTML = '<img src=images/loader-bar.gif />'; doAjaxCall('banner.php?do=create&img='+document.getElementById('picture').value+'&heading='+document.getElementById('heading_txt').value+'&subheading='+document.getElementById('subheading_txt').value+'&sid='+Math.random(), 'msg'); return true;" /></td>
59  </tr>
60</table>
61</div>
62<div id="picture_preview"></div>
63</body>
64</html>
file : js.js => fungsi-fungsi javascript
01function doAjaxCall(the_request, targeTo) {
02    var request = null;
03    if (window.XMLHttpRequest) {
04        request = new XMLHttpRequest();
05    } else if (window.ActiveXObject) {
06        request = new ActiveXObject("Microsoft.XMLHTTP");
07    }
08    if (request) {
09        request.open("GET", the_request);
10        request.onreadystatechange = function() {
11            if (request.readyState == 4) {
12                document.getElementById(targeTo).innerHTML = request.responseText;
13            }
14        }
15        request.send(null);
16    } else {
17        alert("Sorry, Your browser not support ajax.");
18    }
19}
20function ajaxFileUpload(upload_field) {
21    // Checking file type
22    var re_text = /\.jpg|\.gif|\.png|\.jpeg/i;
23    var filename = upload_field.value;
24    if (filename.search(re_text) == -1) {
25        alert("Only jpg/gif/png Are Allowed");
26        upload_field.form.reset();
27        return false;
28    }
29 
30    upload_field.form.action = 'upload.php';
31    upload_field.form.target = 'upload_iframe';
32    upload_field.form.submit();
33    upload_field.form.action = '';
34    upload_field.form.target = '';
35    return true;
36}
37 
38function previewBanner(evt) {
39    document.getElementById('txt_heading_prev').innerHTML=document.getElementById('heading_txt').value;
40    document.getElementById('txt_subheading_prev').innerHTML=document.getElementById('subheading_txt').value;
41}
42 
43function resetDisplay() {
44    document.getElementById('heading_txt').value='';
45    document.getElementById('subheading_txt').value='';
46    document.getElementById('picture').value='';
47    document.getElementById('txt_box').style.display='none';
48    document.getElementById('picture_preview').style.display='none';
49    document.getElementById('picture').disabled='';
50}
file : upload.php => serverside script dipanggil oleh ajax untuk upload file ke directory banners/
01<?php
02$full_serv_path = $_SERVER['HTTP_HOST']."". $_SERVER['REQUEST_URI'];
03$preview_url = "http://".str_replace(basename($full_serv_path), "", $full_serv_path)."banners/"; // get server path for live preview
04$upload_dir = str_replace(basename(__FILE__), "", __FILE__)."banners/"; // location uploaded image will saved
05$filename= '';
06$result = 'ERROR';
07$result_msg = '';
08$allowed_image = array ('image/gif', 'image/jpeg', 'image/jpg', 'image/pjpeg','image/png');
09define('PICTURE_SIZE_ALLOWED', 2242880); // bytes
10 
11if (isset($_FILES['picture'])) {  // file was send from browser
12    if ($_FILES['picture']['error'] == UPLOAD_ERR_OK) {  // no error
13        if (in_array($_FILES['picture']['type'], $allowed_image)) {
14            if(filesize($_FILES['picture']['tmp_name']) <= PICTURE_SIZE_ALLOWED) { // bytes
15                $filename = $_FILES['picture']['name'];
16                move_uploaded_file($_FILES['picture']['tmp_name'], $upload_dir.$filename);
17            } else {
18                die('Picture size is to large');
19            }
20        } else {
21            die('Only jpg/gif/png Are Allowed');
22        }
23    } else {
24        die('Unknown error');
25    }
26}
27 
28    echo '<script language="JavaScript" type="text/javascript">'."\n";
29 
30    if($filename != '') {
31        echo "window.parent.document.getElementById('picture_preview').innerHTML = '<img src=\"images/ajax-loader.gif\" border=\"0\" />';";
32        echo "window.parent.document.getElementById('picture_preview').innerHTML = '<img src=\'$preview_url$filename\' id=\'preview_picture_tag\' name=\'preview_picture_tag\' /><div id=\'txt_heading_prev\' class=\'txt_heading_prev\'></div><div id=\'txt_subheading_prev\' class=\'txt_subheading_prev\'></div>';";
33        echo "window.parent.document.getElementById('picture_preview').style.display = 'block';";
34        echo "window.parent.document.getElementById('txt_box').style.display = 'block';";
35        echo "window.parent.document.getElementById('picture').disabled='true';";
36    }
37 
38    echo "\n".'</script>';
39    exit(); // do not go futher
40 
41?>
file : banner.php => serverside script dipanggil oleh ajax untuk membuat gambar dari file yang di upload dan teks Heading dan Subheading menggunakan GD Library, serta untuk menghapus gambar bila user membatalkan pembuatan banner.
01<?php
02function getImgType($img) {
03    if(substr($img, strlen($img)-4) == ".jpg" || substr($img, strlen($img)-5) == ".jpeg")
04        return "jpg";
05    elseif(substr($img, strlen($img)-4) == ".gif")
06        return "gif";
07    elseif(substr($img, strlen($img)-4) == ".png")
08        return "png";
09    else
10        return false;
11}
12 
13if($_GET['do'] == "create") { // create banner
14  $heading = $_GET['heading'];
15  $subheading = $_GET['subheading'];
16  $imgname = "banners/".$_GET['img'];
17  $img_type = getImgType($_GET['img']);
18  if($img_type== "jpg") {
19      $im = imagecreatefromjpeg($imgname); /* Attempt to open */
20  } elseif($img_type == "gif") {
21      $im = imagecreatefromgif($imgname); /* Attempt to open */
22  } elseif($img_type == "png") {
23      $im = imagecreatefrompng($imgname); /* Attempt to open */
24  } else {
25      die("Only jpg/gif/png Are Allowed");
26  }
27  $font = 'arial.TTF';
28  $_h = 0;
29 
30  $bg = imagecolorallocate($im, 255, 255, 255);
31  $font_color = imagecolorallocate($im, 0, 0, 0);
32  $split_heading = split("[\n]+", $heading);
33  $split_subheading = split("[\n]+", $subheading);
34  $w = imagesx($im);
35  foreach($split_heading as $key=>$val) {
36      $_b = imagettfbbox(18, 0, $font, $val);
37      $_w = abs($_b[2]-$_b[0]);
38      $_x = $w-$_w;
39      $_h = abs($_b[5]-$_b[3]);
40      $_h += $_h;
41      imagettftext($im, 18, 0, $_x-40, 55, $font_color, $font, $val);
42  }
43  foreach($split_subheading as $key=>$val) {
44      $_b = imagettfbbox(11, 0, $font, $val);
45      $_w = abs($_b[2]-$_b[0]);
46      $_x = $w-$_w;
47      $_h = abs($_b[5]-$_b[3]);
48      $_h += $_h;
49      imagettftext($im, 11, 0, $_x-40, 83, $font_color, $font, $val);
50  }
51  if($img_type == "jpg") {
52      $save_banner = imagejpeg($im, $imgname); /* Attempt to save */
53  } elseif($img_type == "gif") {
54      $save_banner = imagegif($im, $imgname); /* Attempt to save */
55  } elseif($img_type == "png") {
56      $save_banner = imagepng($im, $imgname); /* Attempt to save */
57  } else {
58      die("Only jpg/gif/png Are Allowed");
59  }
60  if($save_banner) {
61      print "Banner Created";
62  } else {
63      print "Failed To Create Banner";
64  }
65 
66} elseif ($_GET['do'] == "cancel") { // cancel creating banner
67    $imgname = "banners/".$_GET['img'];
68    if(unlink($imgname)) { //remove uploaded image
69        echo "Image Removed";
70    } else {
71        print "Error Removing Image";
72    }
73}
74?>
Silahkan anda berkreasi atau mengembangkan aplikasi ini, misalkan dengan menambahkan option untuk warna/besar/align untuk heading dan subheading.
Tergantung kebutuhan. :)

No comments:

Post a Comment