Web Programming: Resize an Image (on the fly) & Keep its Aspect Ratio using PHP and GD

This is a PHP Class useful if you need to resize images keeping their aspect ratio, using the GD Library. The new height is calculated proportionally to the new width’s size and reverse. For instance you have an image with the following dimensions: width – 1000, height – 800. Its thumbnail with a width of 250 will have the height of 200 (the ratio is kept).

Here’s the class (I will explain you how it works below):

resize.image.class.php

001.<?php
002./*
003.---------------------------------------------------------------------
004.Credits: Bit Repository
005.
007.---------------------------------------------------------------------
008.*/
009.class Resize_Image {
010.
011.var $image_to_resize;
012.var $new_width;
013.var $new_height;
014.var $ratio;
015.var $new_image_name;
016.var $save_folder;
017.
018.function resize()
019.{
020.if(!file_exists($this->image_to_resize))
021.{
022. exit("File ".$this->image_to_resize." does not exist.");
023.}
024.
025.$info = GetImageSize($this->image_to_resize);
026.
027.if(empty($info))
028.{
029. exit("The file ".$this->image_to_resize." doesn't seem to be an image.");
030.}
031.
032.$width = $info[0];
033.$height = $info[1];
034.$mime = $info['mime'];
035.
036./*
037.Keep Aspect Ratio?
038.
039.Improved, thanks to Larry
040.*/
041.
042.if($this->ratio)
043.{
044.// if preserving the ratio, only new width or new height
045.// is used in the computation. if both
046.// are set, use width
047.
048.if (isset($this->new_width))
049.{
050.$factor = (float)$this->new_width / (float)$width;
051.$this->new_height = $factor * $height;
052.}
053.else if (isset($this->new_height))
054.{
055.$factor = (float)$this->new_height / (float)$height;
056.$this->new_width = $factor * $width;
057.}
058.else
059.exit(”neither new height or new width has been set”);
060.}
061.
062.// What sort of image?
063.
064.$type = substr(strrchr($mime, '/'), 1);
065.
066.switch ($type)
067.{
068.case 'jpeg':
069. $image_create_func = 'ImageCreateFromJPEG';
070. $image_save_func = 'ImageJPEG';
071. $new_image_ext = 'jpg';
072. break;
073.
074.case 'png':
075. $image_create_func = 'ImageCreateFromPNG';
076. $image_save_func = 'ImagePNG';
077. $new_image_ext = 'png';
078. break;
079.
080.case 'bmp':
081. $image_create_func = 'ImageCreateFromBMP';
082. $image_save_func = 'ImageBMP';
083. $new_image_ext = 'bmp';
084. break;
085.
086.case 'gif':
087. $image_create_func = 'ImageCreateFromGIF';
088. $image_save_func = 'ImageGIF';
089. $new_image_ext = 'gif';
090. break;
091.
092.case 'vnd.wap.wbmp':
093. $image_create_func = 'ImageCreateFromWBMP';
094. $image_save_func = 'ImageWBMP';
095. $new_image_ext = 'bmp';
096. break;
097.
098.case 'xbm':
099. $image_create_func = 'ImageCreateFromXBM';
100. $image_save_func = 'ImageXBM';
101. $new_image_ext = 'xbm';
102. break;
103.
104.default:
105. $image_create_func = 'ImageCreateFromJPEG';
106. $image_save_func = 'ImageJPEG';
107. $new_image_ext = 'jpg';
108.}
109.
110. // New Image
111. $image_c = ImageCreateTrueColor($this->new_width, $this->new_height);
112.
113. $new_image = $image_create_func($this->image_to_resize);
114.
115. ImageCopyResampled($image_c, $new_image, 0, 0, 0, 0, $this->new_width, $this->new_height, $width, $height);
116.
117. if($this->save_folder)
118. {
119. if($this->new_image_name)
120. {
121. $new_name = $this->new_image_name.'.'.$new_image_ext;
122. }
123. else
124. {
125. $new_name = $this->new_thumb_name( basename($this->image_to_resize) ).'_resized.'.$new_image_ext;
126. }
127.
128. $save_path = $this->save_folder.$new_name;
129. }
130. else
131. {
132. /* Show the image without saving it to a folder */
133. header("Content-Type: ".$mime);
134.
135. $image_save_func($image_c);
136.
137. $save_path = '';
138. }
139.
140. $process = $image_save_func($image_c, $save_path);
141.
142. return array('result' => $process, 'new_file_path' => $save_path);
143.
144. }
145.
146. function new_thumb_name($filename)
147. {
148. $string = trim($filename);
149. $string = strtolower($string);
150. $string = trim(ereg_replace("[^ A-Za-z0-9_]", " ", $string));
151. $string = ereg_replace("[ tnr]+", "_", $string);
152. $string = str_replace(" ", '_', $string);
153. $string = ereg_replace("[ _]+", "_", $string);
154.
155. return $string;
156. }
157.}
158.?>

Variables Info$image_to_resize – Here we set the full path (i.e. /home/www.mysite.com/public_html/images/myimage.jpg) to the image we wish to resize. If the image is in the same folder with the class, then you can just set the filename as the path (i.e. mywallpaper.jpg).

The $new_width & $new_height are the new dimensions for the resized image.

$ratio – Do you wish to keep the image’s ratio aspect after resize? If it’s set to true it will calculate the new dimensions based on the new width (if it’s bigger than the height) or the new height (if it’s bigger than width).

$new_image_name – It’s used to set a name for the new resized image. If it’s not set a name will be assigned automatically.

$save_folder – The path to the folder where the new image will be saved. Make sure it’s writable (0777). It no folder is set the new image will show in the browser without being saved.
Here’s an example of how you can use this class:

01.<?php
02.include 'resize.image.class.php';
03.
04.$image = new Resize_Image;
05.
06.$image->new_width = 200;
07.$image->new_height = 200;
08.
09.$image->image_to_resize = "/home/mysite.com/public_html/images/sunset_wallpaper.jpg"; // Full Path to the file
10.
11.$image->ratio = true; // Keep Aspect Ratio?
12.
13.// Name of the new image (optional) - If it's not set a new will be added automatically
14.
15.$image->new_image_name = 'sunset_wallpaper_thumbnail';
16.
17./* Path where the new image should be saved. If it's not set the script will output the image without saving it */
18.
19.$image->save_folder = 'thumbs/';
20.
21.$process = $image->resize();
22.
23.if($process['result'] && $image->save_folder)
24.{
25.echo 'The new image ('.$process['new_file_path'].') has been saved.';
26.}
27.?>

How to invoke this class to generate thumbnails in a HTML page?

This class has an advantage: you can resize images ‘on the fly’ with it. This way you don’t have to necessarily save the resized image on the server. You can just output it. Here’s how you can call this class from a HTML page without using any PHP code in it:

demo.html

01.<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
02.<html>
03. <head>
04. <title> Show Resized Image </title>
05. <meta name="Author" content="Bit Repository">
06. <meta name="Keywords" content="src, image, resize, on the fly">
07. <meta name="Description" content="Display a resized image">
08. </head>
09. <body>
10. <img src="resize_image.php?image=sunset.jpg&new_width=200&new_height=200">
11. </body>
12.</html>

As you can see, the resize_image.php script is called. Some info is needed to make the resize: original image (‘image’), a width (‘new_width’) and a height (‘new_height’). In many cases, if the ‘ratio aspect’ is enabled, you can specify only one measurement. The new dimensions will be calculated based on whether you choose: width or height. Here’s the resize_image.php script:

resize_image.php

01.<?php
02.set_time_limit(10000);
03.
04.error_reporting(E_ALL ^ E_NOTICE);
05.
06.include 'resize.image.class.php';
07.
08.$resize_image = new Resize_Image;
09.
10.// Folder where the (original) images are located with trailing slash at the end
11.$images_dir = 'images/';
12.
13.// Image to resize
14.$image = $_GET['image'];
15.
16./* Some validation */
17.if(!@file_exists($images_dir.$image))
18.{
19.exit('The requested image does not exist.');
20.}
21.
22.// Get the new with & height
23.$new_width = (int)$_GET['new_width'];
24.$new_height = (int)$_GET['new_height'];
25.
26.$resize_image->new_width = $new_width;
27.$resize_image->new_height = $new_height;
28.
29.$resize_image->image_to_resize = $images_dir.$image; // Full Path to the file
30.
31.$resize_image->ratio = true; // Keep aspect ratio
32.
33.$process = $resize_image->resize(); // Output image
34.?>

source: http://www.bitrepository.com/resize-an-image-keeping-its-aspect-ratio-using-php-and-gd.html

Advertisements

Web Programming: Number Format (php, Javascript)

Wuihh,.. agak ribet juga ngakalin supaya tampilan number format uang ke database (int) dan tampilin ke client.

Contoh: di database 100000 dan di client: 100,000

di client: (javascript) – hasil nyari2 di mbah google

<script type=”text/javascript”>
function calculate2(objA)
{ setFormat(objA);
var x_price = document.fproductedit.x_price.value.replace(/,/g,”);
//var dp = document.loandata.dp.value.replace(/,/g,”);
//if (!(isNaN(otr) && isNaN(dp)))
//document.loandata.principal.value = formatThous(Number(otr) – Number(dp));

}
function round(x) { return Math.round(x*100)/100;}

formatThous.rejectSign = true;
formatThous.stripSign = true;

function formatThous(num){
var f = formatThous;
if (isNaN(parseFloat(num)) || (f.rejectSign && /(\+)|(-)/.test(num.toString(10))) || num.toString(10).split(‘.’).length > 2)
{
return num;
}

var l, c = 1, t = ”,
sign = /^(\+)|(-)/.test(num.toString(10).charAt(0)) && !f.stripSign? num.toString(10).charAt(0) : ”;
num = num.toString(10).replace(/[^\d\.]/g, ”).split(‘.’);
l = num[0].length-1;
while (l + 1){
t = c%3||!l? num[0].charAt(l) + t : ‘,’ + num[0].charAt(l) + t;
l–;
c++;
}
return sign + t + (num[1] && num[1].length? ‘.’ + num[1] : ”);
}

function setFormat(objA)
{
if (objA!=”)
{ var a = eval(‘document.fproductedit.’ + objA);
a.value = formatThous(a.value);
}
}

document.fproductedit.x_price.focus();

</script>

dengan form-nya:

<form name=”fproductedit” id=”fproductedit” action=”productedit.php” method=”post” enctype=”multipart/form-data”>

dan

Rp<input type=”text” style=”text-align: right;” onkeyup=”calculate2(this.name);” size=”12″ name=”x_price” id=”x_price” value=”<?php echo number_format($x_price, 0,’,’,’.’);?>”>

Jadi tampilan pada saat input-ing dan tarik dari database itu selalu dibubuhi koma, koma. :-bd

kemudian storing ke database-nya:

$theValue = str_replace(“,”, “”, $theValue);
$fieldList[“`harga`”] = $theValue;

Mudah2an bermanfaat.

Web Programming: Previewing about to be uploaded Image

Image upload & preview without page refresh

August 13, 2009

File upload without refresh:

If you want to have preview option while selecting the file from your local machine, The below two scripts will helps to achieve your requirement. You can find the form in “index.html” file. When you selects any file it will call JS function “ajaxFileUpload”. Inside of this function we have set form target to iframe.

upload-picture.php acts as a action page. You can see the uploading stuff over there. You can also find the virus scanning(clamscan) in this file.


File 1: index.html

<script>
function ajaxFileUpload(upload_field)
{
// Checking file type
var re_text = /\.jpg|\.gif|\.jpeg/i;
var filename = upload_field.value;
if (filename.search(re_text) == -1) {
alert("File should be either jpg or gif or jpeg");
upload_field.form.reset();
return false;
}
document.getElementById('picture_preview').innerHTML = '<div><img src="images/progressbar.gif" border="0" /></div>';
upload_field.form.action = 'upload-picture.php';
upload_field.form.target = 'upload_iframe';
upload_field.form.submit();
upload_field.form.action = '';
upload_field.form.target = '';
return true;
}
</script>

<!-- iframe used for ajax file upload-->
<!-- debug: change it to style="display:block" -->
<iframe name="upload_iframe" id="upload_iframe" style="display:none;"></iframe>
<!-- iframe used for ajax file upload-->

<form name="pictureForm" method="post" autocomplete="off" enctype="multipart/form-data">
<div>
<span>Upload Picture :</span>
<input type="file" name="picture" id="picture" onchange="return ajaxFileUpload(this);" />
<span id="picture_error"></span>
<div id="picture_preview"></div>
</div>
</form>

File 2: upload-picture.php

<?php
$upload_dir = '/var/www/file-upload/upload/'; // Directory for file storing
$preview_url = 'http://localhost/file-upload/upload/';
$filename= '';
$result = 'ERROR';
$result_msg = '';
$allowed_image = array ('image/gif', 'image/jpeg', 'image/jpg', 'image/pjpeg','image/png');
define('PICTURE_SIZE_ALLOWED', 2242880); // bytes

if (isset($_FILES['picture']))  // file was send from browser
{
 if ($_FILES['picture']['error'] == UPLOAD_ERR_OK)  // no error
 {
 if (in_array($_FILES['picture']['type'], $allowed_image)) {
 if(filesize($_FILES['picture']['tmp_name']) <= PICTURE_SIZE_ALLOWED) // bytes
 {
 $filename = $_FILES['picture']['name'];
 move_uploaded_file($_FILES['picture']['tmp_name'], $upload_dir.$filename);

//phpclamav clamscan for scanning viruses
//passthru('clamscan -d /var/lib/clamav --no-summary '.$upload_dir.$filename, $virus_msg); //scan virus
$virus_msg = 'OK'; //assume clamav returing OK.
if ($virus_msg != 'OK') {
unlink($upload_dir.$filename);
$result_msg = $filename." : ".FILE_VIRUS_AFFECTED;
$result_msg = '<font color=red>'.$result_msg.'</font>';
$filename = '';
}else {
// main action -- move uploaded file to $upload_dir
$result = 'OK';
}
}else {
$filesize = filesize($_FILES['picture']['tmp_name']);// or $_FILES['picture']['size']
$filetype = $_FILES['picture']['type'];
$result_msg = PICTURE_SIZE;
}
}else {
$result_msg = SELECT_IMAGE;
}
}
elseif ($_FILES['picture']['error'] == UPLOAD_ERR_INI_SIZE)
$result_msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
else
$result_msg = 'Unknown error';
}

// This is a PHP code outputing Javascript code.
echo '<script language="JavaScript" type="text/javascript">'."\n";
echo 'var parDoc = window.parent.document;';
if ($result == 'OK') {
echo 'parDoc.getElementById("picture_error").innerHTML =  "";';
}
else {
echo "parDoc.getElementById('picture_error').innerHTML = '".$result_msg."';";
}

if($filename != '') {
echo "parDoc.getElementById('picture_preview').innerHTML = '<img src=\'$preview_url$filename\' id=\'preview_picture_tag\' name=\'preview_picture_tag\' />';";
}

echo "\n".'</script>';
exit(); // do not go futher

?>

Note:
1. Make sure that the upload directory having the permission.
2. To debug, you need to change the style=”display:block” in iframe tag.

Source: http://web4us.wordpress.com/2009/08/13/image-upload-preview-without-page-refresh