RSS

How to Resize Image Dynamically in PHP

Today almost every website you visit show content in form of thumbnails. Thumbnails are nothing but images displayed next to the content. Be it News website or a blog, displaying images next to content is key to appeal user. Even our blog shows images as thumbnails on home page.

A prerequisites to show Thumbnail in a webpage is that thumbnail must be small enough. So that many thumbnails can be loaded as fast as possible. Hence almost every website resize the image to create small thumbnails.

So how to do this on the fly? How to resize an Image dynamically in PHP?

There is an extremely useful PHP library called timthumb which comes very handy. It’s just a simple PHP script that you need to download and put in some folder under your website. And then simply call it with appropriate arguments.

  1. Download timthumb.php and put under any folder.
  2. Upload this script timthumb.php though FTP to your web hosting. Put it under a directory /script.
  3. Just call timthumb.php with appropriate arguments, For example:
    <img src="/script/timthumb.php?src=/some/path/myimage.png&w=100&h=80"
        alt="resized image" />

And that’s all!!

One thing worth noting here is that this library will create a folder cache in the directory where timthumb.php script resides. This folder will cache the resized image for better performance.

You can refer following table for different parameters and its meaning.

Parameter Values Meaning
src source url to image Tells TimThumb which image to resize
w width the width to resize to Remove the width to scale proportionally (will then need the height)
h height the height to resize to Remove the height to scale proportionally (will then need the width)
q quality 0 – 100 Compression quality. The higher the number the nicer the image will look. I wouldn’t recommend going any higher than about 95 else the image will get too large
a alignment c, t, l, r, b, tl, tr, bl, br Crop alignment. c = center, t = top, b = bottom, r = right, l = left. The positions can be joined to create diagonal positions
zc zoom / crop 0, 1, 2, 3 Change the cropping and scaling settings
f filters too many to mention Let’s you apply image filters to change the resized picture. For instance you can change brightness/ contrast or even blur the image
s sharpen Apply a sharpen filter to the image, makes scaled down images look a little crisper
cc canvas colour hexadecimal colour value (#ffffff) Change background colour. Most used when changing the zoom and crop settings, which in turn can add borders to the image.
ct canvas transparency true (1) Use transparency and ignore background colour

Hope this is useful for you :)

 
 

Add Youtube video in your WordPress page/post

http://www.mediafire.com/download/c3gx88l0b3m5r4u/pagevideo.zip

This plugin create a youtube button on WordPress editor. If you want add youtube video in your page or post click on that button one popup will open enter video id, height, width and title of video in following format

videoid|height|width|title

example

as-H0sZbbd0|300|300|Pluto

then click on ok button. Short code for that video will generate.

Thanks…

 
Leave a comment

Posted by on July 5, 2013 in Wordpress

 

Create image thumb

$this->thumb($_FILES[‘logofile’][‘tmp_name’], ‘images/logo.png”, $logowidth, $logoheight);

function thumb($file, $save, $width, $height)
{
@unlink($save);

if (!$infos = @getimagesize($file)) {
return false;
}

$iWidth = $infos[0];
$iHeight = $infos[1];

//$iRatioW = $width / $iWidth;
//$iRatioH = $height / $iHeight;

//$iNewH = $height;

if(!empty($height))
$iNewH = $height;

if(!empty($width))
$iNewW = $width;

if(empty($height))
$iNewH = ($iHeight/$iWidth)*$iNewW;

///Condition if width blank then set autowidth… otherwise set passing width…
if(empty($width))
$iNewW = ($iWidth/$iHeight)*$iNewH;

//Don’t resize images which are smaller than thumbs
if ($infos[0] < $width && $infos[1] < $height) {
$iNewW = $infos[0];
$iNewH = $infos[1];
}

if($infos[2] == 1) {

$imgA = imagecreatefromgif($file);
$imgB = imagecreate($iNewW,$iNewH);

if(function_exists(‘imagecolorsforindex’) && function_exists(‘imagecolortransparent’)) {
$transcolorindex = imagecolortransparent($imgA);
//transparent color exists
if($transcolorindex >= 0 ) {
$transcolor = imagecolorsforindex($imgA, $transcolorindex);
$transcolorindex = imagecolorallocate($imgB, $transcolor[‘red’], $transcolor[‘green’], $transcolor[‘blue’]);
imagefill($imgB, 0, 0, $transcolorindex);
imagecolortransparent($imgB, $transcolorindex);
//fill white
} else {
$whitecolorindex = @imagecolorallocate($imgB, 255, 255, 255);
imagefill($imgB, 0, 0, $whitecolorindex);
}
//fill white
} else {
$whitecolorindex = imagecolorallocate($imgB, 255, 255, 255);
imagefill($imgB, 0, 0, $whitecolorindex);
}
imagecopyresampled($imgB, $imgA, 0, 0, 0, 0, $iNewW, $iNewH, $infos[0], $infos[1]);
imagegif($imgB, $save);

} elseif($infos[2] == 2) {

$imgA = imagecreatefromjpeg($file);
$imgB = imagecreatetruecolor($iNewW,$iNewH);
imagecopyresampled($imgB, $imgA, 0, 0, 0, 0, $iNewW, $iNewH, $infos[0], $infos[1]);
imagejpeg($imgB, $save);

} elseif($infos[2] == 3) {
/*
* Image is typ png
*/
$imgA = imagecreatefrompng($file);
$imgB = imagecreatetruecolor($iNewW, $iNewH);
imagealphablending($imgB, false);
imagecopyresampled($imgB, $imgA, 0, 0, 0, 0, $iNewW, $iNewH, $infos[0], $infos[1]);
imagesavealpha($imgB, true);
imagepng($imgB, $save);

} else {
return false;
}
return true;
}

 
1 Comment

Posted by on April 17, 2013 in Joomla

 

Authorize.net recurring payment example

<?php
class AuthnetARB {
var $login;
var $transkey;
var $test;

var $params   = array();
var $success   = false;
var $error    = true;

var $url;
var $xml;
var $response;
var $resultCode;
var $code;
var $text;
var $subscrId;

function AuthnetARB($login, $transkey, $test) {

$this->login = $login;
$this->transkey = $transkey;
$this->test = $test;

$subdomain = ($this->test) ? ‘apitest’ : ‘api’;
$this->url = “https://&#8221; . $subdomain . “.authorize.net/xml/v1/request.api”;
}

function getString() {
if (!$this->params) {
return (string) $this;
}

$output  = “”;
$output .= ‘<table summary=”Authnet Results” id=”authnet”>’ . “\n”;
$output .= ‘<tr>’ . “\n\t\t” . ‘<th colspan=”2″><b>Outgoing Parameters</b></th>’ . “\n” . ‘</tr>’ . “\n”;

foreach ($this->params as $key => $value) {
$output .= “\t” . ‘<tr>’ . “\n\t\t” . ‘<td><b>’ . $key . ‘</b></td>’;
$output .= ‘<td>’ . $value . ‘</td>’ . “\n” . ‘</tr>’ . “\n”;
}

$output .= ‘</table>’ . “\n”;
return $output;
}

function process($retries = 3) {
$count = 0;
while ($count < $retries)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array(“Content-Type: text/xml”));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->xml);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$this->response = curl_exec($ch);
$this->parseResults();
if ($this->resultCode === “Ok”) {
$this->success = true;
$this->error   = false;
break;
} else {
$this->success = false;
$this->error   = true;
break;
}
$count++;
}
curl_close($ch);
}

function createAccount() {
$this->xml = “<?xml version=’1.0′ encoding=’utf-8′?>
<ARBCreateSubscriptionRequest xmlns=’AnetApi/xml/v1/schema/AnetApiSchema.xsd’>
<merchantAuthentication>
<name>” . $this->login . “</name>
<transactionKey>” . $this->transkey . “</transactionKey>
</merchantAuthentication>
<refId>” . $this->params[‘refID’] .”</refId>
<subscription>
<name>”. $this->params[‘subscrName’] .”</name>
<paymentSchedule>
<interval>
<length>”. $this->params[‘interval_length’] .”</length>
<unit>”. $this->params[‘interval_unit’] .”</unit>
</interval>
<startDate>” . $this->params[‘startDate’] . “</startDate>
<totalOccurrences>”. $this->params[‘totalOccurrences’] . “</totalOccurrences>
<trialOccurrences>”. $this->params[‘trialOccurrences’] . “</trialOccurrences>
</paymentSchedule>
<amount>”. $this->params[‘amount’] .”</amount>
<trialAmount>” . $this->params[‘trialAmount’] . “</trialAmount>
<payment>
<creditCard>
<cardNumber>” . $this->params[‘cardNumber’] . “</cardNumber>
<expirationDate>” . $this->params[‘expirationDate’] . “</expirationDate>
</creditCard>
</payment>
<order>
<invoiceNumber>” . $this->params[‘orderInvoiceNumber’] . “</invoiceNumber>
<description>” . $this->params[‘orderDescription’] . “</description>
</order>
<customer>
<id>” . $this->params[‘customerId’] . “</id>
<email>” . $this->params[‘customerEmail’] . “</email>
</customer>
<billTo>
<firstName>”. $this->params[‘firstName’] . “</firstName>
<lastName>” . $this->params[‘lastName’] . “</lastName>
<address>” . $this->params[‘address’] . “</address>
<city>” . $this->params[‘city’] . “</city>
<state>” . $this->params[‘state’] . “</state>
<zip>” . $this->params[‘zip’] . “</zip>
<country>” . $this->params[‘country’] . “</country>
</billTo>”;

if($this->params[‘shippinginfo’])
{
$this->xml .= “<shipTo>
<firstName>”. $this->params[‘sfirstName’] . “</firstName>
<lastName>” . $this->params[‘slastName’] . “</lastName>
<address>” . $this->params[‘saddress’] . “</address>
<city>” . $this->params[‘scity’] . “</city>
<state>” . $this->params[‘sstate’] . “</state>
<zip>” . $this->params[‘szip’] . “</zip>
<country>” . $this->params[‘scountry’] . “</country>
</shipTo>”;
}

$this->xml .= “</subscription>
</ARBCreateSubscriptionRequest>”;
$this->process();
}

function updateAccount() {
$this->xml = “<?xml version=’1.0′ encoding=’utf-8′?>
<ARBUpdateSubscriptionRequest xmlns=’AnetApi/xml/v1/schema/AnetApiSchema.xsd’>
<merchantAuthentication>
<name>” . $this->login . “</name>
<transactionKey>” . $this->transkey . “</transactionKey>
</merchantAuthentication>
<refId>” . $this->params[‘refID’] .”</refId>
<subscriptionId>” . $this->params[‘subscrId’] . “</subscriptionId>
<subscription>
<amount>”. $this->params[‘amount’] .”</amount>

<billTo>
<firstName>”. $this->params[‘firstName’] . “</firstName>
<lastName>” . $this->params[‘lastName’] . “</lastName>
<address>” . $this->params[‘address’] . “</address>
<city>” . $this->params[‘city’] . “</city>
<state>” . $this->params[‘state’] . “</state>
<zip>” . $this->params[‘zip’] . “</zip>
<country>” . $this->params[‘country’] . “</country>
</billTo>”;

if($this->params[‘shippinginfo’])
{
$this->xml .= “<shipTo>
<firstName>”. $this->params[‘sfirstName’] . “</firstName>
<lastName>” . $this->params[‘slastName’] . “</lastName>
<address>” . $this->params[‘saddress’] . “</address>
<city>” . $this->params[‘scity’] . “</city>
<state>” . $this->params[‘sstate’] . “</state>
<zip>” . $this->params[‘szip’] . “</zip>
<country>” . $this->params[‘scountry’] . “</country>
</shipTo>”;
}
$this->xml .= “</subscription>
</ARBUpdateSubscriptionRequest>”;
$this->process();
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//

function updateFirst() {
$this->xml = “<?xml version=’1.0′ encoding=’utf-8′?>
<ARBUpdateSubscriptionRequest xmlns=’AnetApi/xml/v1/schema/AnetApiSchema.xsd’>
<merchantAuthentication>
<name>” . $this->login . “</name>
<transactionKey>” . $this->transkey . “</transactionKey>
</merchantAuthentication>
<refId>” . $this->params[‘refID’] .”</refId>
<subscriptionId>” . $this->params[‘subscrId’] . “</subscriptionId>
<subscription>
<paymentSchedule>
<interval>
<length>”. $this->params[‘interval_length’] .”</length>
<unit>”. $this->params[‘interval_unit’] .”</unit>
</interval>
<startDate>” . $this->params[‘startDate’] . “</startDate>
<totalOccurrences>”. $this->params[‘totalOccurrences’] . “</totalOccurrences>
<trialOccurrences>”. $this->params[‘trialOccurrences’] . “</trialOccurrences>
</paymentSchedule>
<amount>”. $this->params[‘amount’] .”</amount>
</subscription>
</ARBUpdateSubscriptionRequest>”;
$this->process();
}

function updateAmount() {
$this->xml = “<?xml version=’1.0′ encoding=’utf-8′?>
<ARBUpdateSubscriptionRequest xmlns=’AnetApi/xml/v1/schema/AnetApiSchema.xsd’>
<merchantAuthentication>
<name>” . $this->login . “</name>
<transactionKey>” . $this->transkey . “</transactionKey>
</merchantAuthentication>
<refId>” . $this->params[‘refID’] .”</refId>
<subscriptionId>” . $this->params[‘subscrId’] . “</subscriptionId>
<subscription>
<amount>”. $this->params[‘amount’] .”</amount>
</subscription>
</ARBUpdateSubscriptionRequest>”;
$this->process();
}

//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//
function deleteAccount() {
$this->xml = “<?xml version=’1.0′ encoding=’utf-8′?>
<ARBCancelSubscriptionRequest xmlns=’AnetApi/xml/v1/schema/AnetApiSchema.xsd’>
<merchantAuthentication>
<name>” . $this->login . “</name>
<transactionKey>” . $this->transkey . “</transactionKey>
</merchantAuthentication>
<refId>” . $this->params[‘refID’] .”</refId>
<subscriptionId>” . $this->params[‘subscrId’] . “</subscriptionId>
</ARBCancelSubscriptionRequest>”;
$this->process();
}

function parseResults() {
$this->resultCode = $this->substring_between($this->response,'<resultCode>’,'</resultCode>’);
$this->code = $this->substring_between($this->response,'<code>’,'</code>’);
$this->text = $this->substring_between($this->response,'<text>’,'</text>’);
$this->subscrId = $this->substring_between($this->response,'<subscriptionId>’,'</subscriptionId>’);
}

function substring_between($haystack,$start,$end) {
if (strpos($haystack,$start) === false || strpos($haystack,$end) === false) {
return false;
} else {
$start_position = strpos($haystack,$start)+strlen($start);
$end_position = strpos($haystack,$end);
return substr($haystack,$start_position,$end_position-$start_position);
}
}

function setParameter($field = “”, $value = null) {
$field = (is_string($field)) ? trim($field) : $field;
$value = (is_string($value)) ? trim($value) : $value;

if (!is_string($field)) {
die(“setParameter() arg 1 must be a string or integer: ” . gettype($field) . ” given.”);
}

if (!is_string($value) && !is_numeric($value) && !is_bool($value)) {

die(“setParameter() arg 2 must be a string, integer, or boolean value: ” . gettype($value) . ” given.”);
}

if (empty($field)) {
die(“setParameter() requires a parameter field to be named.”);
}

if ($value === “”) {
die(“setParameter() requires a parameter value to be assigned: $field”);
}

$this->params[$field] = $value;
}

function isSuccessful() {
return $this->success;
}

function isError() {
return $this->error;
}

function getResponse() {
return $this->text;
}

function getRawResponse() {
return $this->response;
}

function getResultCode() {
return $this->resultCode;
}

function getSubscriberID() {
return $this->subscrId;
}
}

$arb = new AuthnetARB($apiloginid, $transkey, $paymentmode);

$arb->setParameter(‘trialOccurrences’, 0);
$arb->setParameter(‘trialAmount’, 0.00);
$arb->setParameter(‘amount’, $product_amt);

$arb->setParameter(‘refId’, 115);
$arb->setParameter(‘cardNumber’, $_POST[‘creditcard’] );
$arb->setParameter(‘cardCode’, $_POST[‘CVV2’] );
$arb->setParameter(‘expirationDate’, $_POST[‘expyear’].”-“.$_POST[‘expmonth’] );
$arb->setParameter(‘orderInvoiceNumber’,date(‘YmdHisu’));
$arb->setParameter(‘orderInvoiceNumber’,date(‘YmdHis’));
$arb->setParameter(‘orderDescription’, ‘Order Description’);
$arb->setParameter(‘customerEmail’, $userinfo->email);
$arb->setParameter(‘firstName’, $userinfo->firstname);
$arb->setParameter(‘lastName’, $userinfo->lastname);
$arb->setParameter(‘address’, $userinfo->address);
$arb->setParameter(‘city’, $userinfo->city);
$arb->setParameter(‘state’, $userinfo->statetitle);
$arb->setParameter(‘zip’, $userinfo->zip);
$arb->setParameter(‘country’, ‘Uniteted State’);

if($shillinginfo)
{
$arb->setParameter(‘shippinginfo’, 1);
$arb->setParameter(‘sfirstName’, $shillinginfo->firstname);
$arb->setParameter(‘slastName’, $shillinginfo->lastname);
$arb->setParameter(‘saddress’, $shillinginfo->address);
$arb->setParameter(‘scity’, $shillinginfo->city);
$arb->setParameter(‘sstate’, $state->state);
$arb->setParameter(‘szip’, $shillinginfo->zip);
$arb->setParameter(‘scountry’, ‘Uniteted State’);
$arb->setParameter(‘ssubscrName’, “Wrinkless Cream” );
}

$arb->setParameter(‘subscrName’, “Wrinkless Cream” );

//$arb->setParameter(‘interval_length’, 30 /*$params->get(‘trialdays’)*/);
$arb->setParameter(‘interval_length’, 30);
$arb->setParameter(‘interval_unit’, ‘days’);
//$arb->setParameter(‘interval_length’, 1);
//$arb->setParameter(‘interval_unit’, ‘months’);
$arb->setParameter(‘startDate’, date(‘Y-m-d’));
$arb->setParameter(‘totalOccurrences’, 9999);
$arb->createAccount();

if($arb->isSuccessful())
{

$db             = JFactory::getDBO();
// insert response into db
$query = “INSERT INTO #__purchase_transactions SET subscriberid=”.$db->Quote($arb->getSubscriberID()).”,
string=”.$db->Quote($arb->getString()).”, response=”.$db->Quote($arb->getResponse()).”,
date=CURDATE(), billingid=”.$id.”, paymenttype=2, expdate=”.$db->Quote($_POST[‘expyear’].”-“.$_POST[‘expmonth’]).”,
paymentmode=”.$db->Quote($paymentmode).”, amount=”.$product_amt.”, cancellationid=”.$db->Quote($arb->getSubscriberID());
//echo $query;die;
$db->setQuery($query);
$db->query();

}

?>

 

 
Leave a comment

Posted by on April 5, 2013 in Joomla

 

Print the div content using Javascript

var DocumentContainer = document.getElementById(‘divid’);
var WindowObject = window.open(”, ‘PrintWindow’, ‘width=940,height=500,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes’);
WindowObject.document.writeln(DocumentContainer.innerHTML);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
WindowObject.close();

 
Leave a comment

Posted by on April 3, 2013 in Javascript

 

Get Joomla database details

$hostname =JFactory::getConfig()->getValue(‘config.host’);

$dbusername = JFactory::getConfig()->getValue(‘config.user’);

$dbpassword = JFactory::getConfig()->getValue(‘config.password’);

$dbname =JFactory::getConfig()->getValue(‘config.db’);

 
Leave a comment

Posted by on April 3, 2013 in Joomla

 

Extract zip file

//jimport( ‘joomla.filesystem.archive’ );

$dateiPfad = JPATH_COMPONENT.DS.’archiv_ordner’;
$dateiName = ‘mein_archiv.tar.gz’;

if( JArchive::extract($dateiPfad.DS.$dateiName, $dateiPfad.DS.’neues_verzeichnis’) )
{
//– Das Archiv wurde erfolgreich entpackt
}
else
{
//– Es trat ein Fehler auf
}

 
Leave a comment

Posted by on April 2, 2013 in Joomla