Beginner’s Guide to Cropping Images in PHP Using ImageMagick

While using images in a web application, developers can’t always include images of a particular measurement. In such cases, resizing the images for the application would be a good option but, not efficient either. For example, resizing a long vertical image into a horizontal dimension would just squeeze the image; thereby, affecting the aesthetics of the website and also reducing the purpose of it. Hence it would be smart to implement a cropping tool like ‘ImageMagick’ in order to fit images of various dimensions into a specified size.

ImageMagick is a collection of robust and convenient tools for manipulating images. It can be used to crop images of numerous formats such as JPEG, PNG, GIF, TIFF, PhotoCD and many more. ImageMagick facilitates creation of dynamic images that are fitting to the specific requirements of web applications.

Difference Between Cropping in GD Library and ImageMagic:

GD is the most commonly used extension for PHP. It is popular because it is easier to install and configure (`yum install php-gd` on Fedora, CentOS etc or `sudo apt-get php5-gd` on ubuntu). However, it has some limitations such as:

  • It is comparatively slower
  • It is more memory intensive
  • For certain aspects it can be more complex to use.

Below I have mentioned a sample code for image cropping using GD:

[sourcecode]<?php
function resize_my_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*($r-$w/$h)));
} else {
$height = ceil($height-($height*($r-$w/$h)));
}
$newGDwidth = $w;
$newGDheight = $h;
} else {
if ($w/$h > $r) {
$newGDwidth = $h*$r;
$newGDheight = $h;
} else {
$newGDheight = $w/$r;
$newGDwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newGDwidth, $newGDheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newGDwidth, $newGDheight, $width, $height);

return $dst;
}

$img = resize_my_image(‘/path/to/some/image.jpg’, 150, 150);
?>[/sourcecode]

You can either output it to the browser or save it to a file using the ‘imagejpeg’ function.

Imagick:

Imagick is a less frequently used PECL extension. ImageMagick is a free tool that is used for creating and manipulating images that supports over 100 different image formats. This can be used on a command line tool for any programming language. The Imagick extension essentially provides an API for all of the functionalities available in the `convert` command line tool.

Some of its advantages are:

  • It is faster
  • It uses less memory
  • Offers more powerful functionality
  • Imagick’ is lot easier to use (once you figure out how), your code may end up smaller and cleaner.

The down side of using this extension is that the documentation is extremely limited and there are almost no examples available on the web. Installation on the other hand can be a painful task as well.

Although it should just be a matter of running the command `pecl install imagick`.

Sample code:

Cropping larger images:

Put a big picture named andolasoft_logo.jpg along side with your php page, run the test and check the directory to see andolasoft_logo_thumb.jpg.

Requirement:

imagemagick with imagick extension

[sourcecode]<?php
$obj = new imagick(‘andolasoft_logo.jpg’);
//resize the above image
$obj->thumbnailImage(160, 0);
//write the thumb
$obj->writeImage(‘andolasoft_logo_thumb.jpg’);
?>[/sourcecode]

To Crop Animated Image:

[sourcecode]<?php
$image = new imagick(“andolasoft_animated_logo.gif”);
$image = $image->coalesceImages(); // the trick! To crop animated image
foreach ($image as $frame) {
$frame->cropImage($width, $height, $x, $y);
$frame->setImagePage(0, 0, 0, 0); // Remove gif canvas
}
?>[/sourcecode]

$x → The X coordinate of the cropped region’s top left corner
$y → The Y coordinate of the cropped region’s top left corner

Implementing ‘ImageMagick’ would make the website look clean and flawless. Images on the other hand retain its look and feel, thereby making the application look professional and optimized.

Find anything amiss here, then share it with us.

CakePHP is Faster Development Of Next Generation Web Application

There are numerous PHP frameworks available such as Zend, CodeIgniter, Akelos etc. CakePHP on the other hand is the most popular framework among them and reduces significant coding time and investment. It is an open source web application development tool. It helps to build the web pages and applications faster and simpler.

Some features of CakePHP framework

  • Compatible with almost all PHP versions
  • Facilitates code scaffolding for faster development of prototypes
  • Doesn’t require any complex configuration
  • This framework is safe and secure:  It provides in-built tools for input validation, XSS prevention, SQL prevention for secure application development.
  • It provides built-in view helpers for AJAX, JavaScript, HTML etc.
  • It offers faster and flexible tempting features as well as data validation features

Never miss an update from us. Join 10,000+ marketers and leaders.

These features make installation and use of CakePHP easy which in turn makes PHP more manageable. As it is an open source, it can be customized according to the needs of specific business requirements. It provides the CakePHP developers with MVC framework, Class inheritance, re-usability, Ajax support and many more to make the development process easier and effortless.  It assists the PHP developers at all levels and provide the ability to manage every part of project development.

Conclusion

It has a lot of advantages over other PHP frameworks, such as less code, less maintenance, and more scalability. CakePHP team works tirelessly to make sure that programmers who want to use CakePHP can do so in an easy and enjoyable way. CakePHP itself is easy to use, and the framework has many features to make life easier for developers who need to create applications that work well and scale to large numbers of users.

Our CakePHP development team is highly experienced to deliver robust, logical, most reliable and effective solutions to our global clients. Our expertise in CakePHP development helps us for building cost effective apps that too matching customer budget with quick turn-around time.

Why CakePHP is Popular? And The Role Of CakePHP Developer

CakePHP is an open source PHP based rapid development framework. It offers great run-time infrastructure along with abundant set of libraries for CakePHP developers. Cake PHP development is supported by the MVC (Model View and Controller) architecture which differentiates the programming logic from the data presentation layer.

It also features other programming concepts like Front Controller, Association Data Mapping and Active Record. Along with these, there are numerous other features that make CakePHP one of the most preferred web development frameworks among others.

Let’s take a look at some features here

Wide Community:

CakePHP developers are supported by huge peers who make use of this framework. There are many contributors and programmers who share the community. For this reason, using the framework is simpler for development as well as for research.

Never miss an update from us. Join 10,000+ marketers and leaders.

Reusability:

It facilitates the developers in saving a lot of efforts through PHP development. Because the programmer make use of a pre-written code for more than one project. In other words, they can focus on the logical and creative part of application whereas the tedious task of coding could be handled with ease.

Open Source:

The framework is open source, for which the CakePHP developers do not have to spend any amount in the process of development and have complete access to its source code. It also assists the developers in adding robustness and improves performance in web applications.

Some of the roles of CakePHP developers include

    • Manage development efforts and framework efficiently
    • Support product releases
    • Ability to handle lot of projects in less time
    • Overall review of the quality & progress of the work
    • Support stable user growth

Conclusion

Here at Andolasoft we provide our customers with a unique and up-to-date approach towards their Web-app development. We design and develop intriguing web applications using PHP/CakePHP. We follow agile development approach to deliver project on time and within budget to our customer

CloudLinux’s Recent Integration of PHP 5.5 Alpha 2 Version

Shared hosting operating system provider CloudLinux has expanded their PHP offerings by declaring the availability of PHP 5.5 Alpha2 version to its PHP selector tool.

With the ability to select PHP versions, PHP selector allows the users to get the latest feature updates

and preferred PHP version like PHP 5.2, 5.3, 5.4, and now, 5.5 Alpha2 from their web hosting control panel. CloudLinux places each individual website in a virtual private server.

Never miss an update from us. Join 10,000+ marketers and leaders.

Each account is then assigned a specific amount of hardware resources and a desirable PHP version, by using the PHP selector tool.

PHP 5.5 Alpha2 version includes new features like the most awaited password hashing API and providing users the ability to use bcrypt along with loop-controlling generators.

Igor Seletskiy the CEO of CloudLinux has expressed that the availability of PHP selector has made it easier to get access to PHP features. He quoted “PHP is possibly the most widely used aspect of any shared web hosting plan.”

Igor Seletskiy also added “Like the rest of the web hosting community, we are excited to start exploring the new features of PHP version 5.5.

However, many hosting companies and their customers would not usually deploy an Alpha version on a large-scale, server-wide basis.

CloudLinux and PHP Selector make it possible for hosting providers to assign individual accounts their own PHP version without affecting other sites on the same hardware.” Integrating such features in CloudLinux has helped PHP development to become easier and more productive

How To Migrate CakePHP 1.x To 2.x

Today, we will focus on what we need to do to get CakePHP 1.3 application upgraded to CakePHP 2.2.3-the latest official stable release

Installation

This is pretty straight forward, same as CakePHP 1.3 version.
Download and unzip the CakePHP 2.2.3 and follow these below-mentioned instructions.

Configuration

  • core.php
  • Make sure to copy the security.salt and Security.cipher_seed from your old core.php
  • Take notice of how errors, sessions and caching have changed.
  • database.php
  • There is a minor change on this file,
  • CakePHP 1.3: ‘driver’ => ‘mysqli’
  • CakePHP 2.2.3: ‘datasource’ => ‘Database/Mysql’
  • routes.php
  • Don’t overwrite this file with your older one.
  • You can place your custom routes before or after CakePlugin::routes()
  • bootstrap.php
  • Copy all functions, constants and other code from your old bootstrap into the new one.

Folder Structure

  • The cake folder is now inside lib folder. There is nothing to do with this.
  • Files and folders are now CamelCased instead of lower_underscored
  • Example: The “users” folder inside the View becomes “Users”
  • The controller files are now UsersController.php instead of users_controller.php
  • project_user_controller.php becomes “ProjectUsersController.php”
  • The model files are now User.php instead of user.php
  • project_user.php model becomes “ProjectUser.php”
  • The components files are now FormatComponent.php instead of format.php
  • The helpers files are now DatetimeHelper.php instead of datetime.php

Moved APP files

  • The parent app_classes have been moved and renamed as well.
  • Instead of app_controller.php, app_model.php, and app_helper.php now become Controller/AppController.php, Model/AppModel.php, and View/Helper/AppHelper.php.

Auth Component and Login

  • Auth now supports multiple authorization adapters that can all be used together
  • Cake 1.3.x was automatically checking if user has correctly entered username/password inside your login () method of users_controller but in cake 2.x we need to manually call $this->Auth->login () this returns Boolean value based on successful login or failure.

If you are using “email” as your login field name
CakePHP 1.3: (inside AppController beforeFilter)

$this->Auth->fields = array('username' => 'email', 'password' => 'passw

CakePHP 2.2.3: (inside AppController beforeFilter)

$this->Auth->authenticate = array('Form' => array('fields' => array('username' => 'email', 'password' => 'password')));

Auth Login

CakePHP 2.2.3: (inside UsersController login function)

if (!empty($this->request->data)) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
//$this->Session->setFlash('Your Email or Password was incorrect.');
}
}

CakePHP 2.x auth automatically hashes the password on login but not on save.

We can add a beforeSave() method on the User model to hash the password.

public function beforeSave($options = array())
{
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']); return true;
}

Request Data

  • CakePHP 2.0 has done some request related changes.
  • The Request Object does not have “form” element any longer.
  • You will need to replace $this->params[‘form’] with $this->request[‘data’] or $this->request->data.
  • $this->data needs to be replaced with $this->request->data
  • So, now we can use $this->request->data on both form submit and AJAX post.
  • Now, we need to check !empty($this->request->data) instead of “!empty($this->data)” while saving a form.

Views Changes

  • Use $this->Html->link() instead of $html->link()
  • Use $this->Form-> instead of $form->
  • Use $this->Session-> instead of $session->
  • Use $this->Paginator-> intead of $paginator ->
  • For JavaScript inclusion use $this->Html->script(“”) instead of $javascript->link()

Moved Email Elements

  • Email elements have been moved from views/elements to View/Emails.

Helpers

  • The Ajax, Javascript, and XML helpers have been removed. You will need to replace these helper calls with appropriate alternatives
  • Helpers can no longer be called with “$helper->function()”. You need to update your helper calls to use $this->Helper->function()
  • If you are loading or importing your helpers inside another custom helper or component,
  • $myhelper = new DatetimeHelper() becomes $myhelper = new DatetimeHelper($this->_View) or $myhelper = new DatetimeHelper(new View(null))

Components

  • All component files should be extended by Component Class instead of Object

DB and Code Caution

  • There is no Enum Support in cakephp2.x as sql server doesnt have similar datatype.
  • You can change enum to tinyint(2)
  • In cake 1.3 used tinyint(1) for is_active database fields.
  • While retrieveing from database it returns 0/1
  • But, cakePHP2.x no longer returns as 0. This will return bool(true) /bool(false)
  • Boolean column values will be casted to php native boolean type automatically.

__() Function and Pagination

  • The __() function no longer has the option to echo. It always returns
  • Change the Pagination code,

CakePHP 1.3:

echo $this->Paginator->counter(array( 'format' => __('Page %page% of %pages%, showing %current% records out of %count% total, starting on record %start%, ending on %end%'', true)));

CakePHP 2.2.3:

echo $this->Paginator->counter(array( 'format' => __('Page %page% of %pages%, showing %current% records out of %count% total, starting on record %start%, ending on %end%'')));

How To Generate PDF File In CakePHP

TCPDF is a free and open source software one of the widely used PHP libraries in the world. This is because of the fact that it already included in the most popular PHP-based CMS and applications including CakePHPHow to generate pdf file in cakephp.

The installation is pretty straight forward and easy-to-use in CakePHP Framework. Many web applications use this as output documents like invoices, contracts or just web pages in the PDF format.

 

Following are the steps to integrate TCPDF in CakePHP MVC framework.

Step 1:

  • Go to http://www.tcpdf.org and download the latest version of TCPDF zip file.
  • Then unzip the zip file and save under the Vendor folder in cakephp framework(app\vendors)
  • This creates a directory tcpdf there with tcpdf.php and more in it (app\vendors\tcpdf)
  •  You can configure the PDF file Like header Logo Image, Page Title, page Margin etc. in the TCPDF configure file (app->vendors->tcpdf-> tcpdf_config.php)

Step 2:

You can create your own header and footer page of your PDF file. Create a page “xtcpdf.php” under app/vendors with these contents as shown below.

App::import('Vendor','tcpdf/tcpdf');
class XTCPDF extends TCPDF
{
var $xheadertext = 'PDF created using CakePHP and TCPDF';
var $xheadercolor = array(0,0,200);
var $xfootertext = 'Copyright © %d XXXXXXXXXXX. All rights reserved.';
var $xfooterfont = PDF_FONT_NAME_MAIN ;
var $xfooterfontsize = 8 ;
/* Change header text and font size as per your requirement in the above variable*******/
function Header()
{
list($r, $b, $g) = $this->xheadercolor;
$this->setY(10); // shouldn't be needed due to page margin, but helas, otherwise it's at the page top
$this->SetFillColor($r, $b, $g);
$this->SetTextColor(0 , 0, 0);
$this->Cell(0,20, '', 0,1,'C', 1);
$this->Text(15,26,$this->xheadertext );
}
function Footer()
{
$year = date('Y');
$footertext = sprintf($this->xfootertext, $year);
$this->SetY(-20);
$this->SetTextColor(0, 0, 0);
$this->SetFont($this->xfooterfont,'',$this->xfooterfontsize);
$this->Cell(0,8, $footertext,'T',1,'C');
}
}
?>

Step 3:

Create your layout under app/views/layouts/pdf.ctp;

header("Content-type: application/pdf");
echo $content_for_layout;
?>

Step 4:

Here is the Controller code which will display output code of generating PDF file;

function view_pdf($id = null) {
if (!$id) {
$this->Session->setFlash('Sorry, there was no PDF selected.');
$this->redirect(array('action'=>'index'), null, true);
}
$this->layout = 'pdf'; //this will use the pdf.ctp layout
$this->render();
}

Step 5:

Create a page under your view directory (app/views/) named as “view_pdf.ctp” (this name can be change as per your controller method) and write your HTML code/PHP code.