768x90 Getting Online Shouldn't be Tough- $7.49 .com Domains at Go Daddy

Resize image to squared in CakePHP

The code is almost closer with my previous article, just change function resize_image to square_image


function crop_img($imgname, $scale, $filename) {

$filetype = $this->getFileExtension($imgname);

$filetype = strtolower($filetype);


switch($filetype){


case "jpeg":


case "jpg":


$img_src = ImageCreateFromjpeg ($imgname);


break;


case "gif":


$img_src = imagecreatefromgif ($imgname);


break;


case "png":


$img_src = imagecreatefrompng ($imgname);


break;


}


$width = imagesx($img_src);


$height = imagesy($img_src);


$ratiox = $width / $height * $scale;


$ratioy = $height / $width * $scale;


//-- Calculate resampling


$newheight = ($width <= $height) ? $ratioy : $scale;


$newwidth = ($width <= $height) ? $scale : $ratiox;


//-- Calculate cropping (division by zero)


$cropx = ($newwidth - $scale != 0) ? ($newwidth - $scale) / 2 : 0;


$cropy = ($newheight - $scale != 0) ? ($newheight - $scale) / 2 : 0;


//-- Setup Resample & Crop buffers


$resampled = imagecreatetruecolor($newwidth, $newheight);


$cropped = imagecreatetruecolor($scale, $scale);


//-- Resample


imagecopyresampled($resampled, $img_src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);


//-- Crop


imagecopy($cropped, $resampled, 0, 0, $cropx, $cropy, $newwidth, $newheight);


// Save the cropped image


switch($filetype)


{


case "jpeg":


case "jpg":


imagejpeg($cropped,$filename,80);


break;


case "gif":


imagegif($cropped,$filename,80);


break;


case "png":


imagepng($cropped,$filename,80);


break;


}


}

function crop_img($tempFile, $scale, $newFile) {

$filetype = $this->getFileExtension($tempFile);

$filetype = strtolower($tempFile);

switch($filetype) {

case "jpeg":

case "jpg":

 $img_src = imagecreatefromjpeg($tempFile);

 break;

case "gif":

$img_src = imagecreatefromgif ($tempFile);

break;

case "png":

$img_src = imagecreatefrompng ($tempFile);

case "bmp":

$img_src = imagecreatefromwbmp ($tempFile);

break;

}

$width = imagesx($img_src);

$height = imagesy($img_src);

$scale = explode('x',strtolower($size));

$ratiox = $width / $height * $scale[0];

$ratioy = $height / $width * $scale[0];

//-- Calculate resampling

$newheight = ($width <= $height) ? $ratioy : $scale[0];

$newwidth = ($width <= $height) ? $scale[0] : $ratiox;

//-- Calculate cropping (division by zero)

$cropx = ($newwidth - $scale != 0) ? ($newwidth - $scale) / 2 : 0;

$cropy = ($newheight - $scale != 0) ? ($newheight - $scale) / 2 : 0;

//-- Setup Resample & Crop buffers

$resampled = imagecreatetruecolor($newwidth, $newheight);

$cropped = imagecreatetruecolor($scale[0], $scale[0]);

//-- Resample

imagecopyresampled($resampled, $img_src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

//-- Crop

imagecopy($cropped, $resampled, 0, 0, $cropx, $cropy, $newwidth, $newheight);

// Save the cropped image

switch($filetype)

{

case "jpeg":

case "jpg":

imagejpeg($cropped,$newFile,80);

break;

case "gif":

imagegif($cropped,$newFile,80);

break;

case "png":

imagepng($cropped,$newFile,80);

break;

}

}

Upload and Resize Image in CakePHP

I have spent many hours to see articles about resizing and uploading image in cakePHP, almost of them are sounding sucks for me like resizing on View by accessing or injecting the url or copy paste by another written without testing code. Event I was trying to convert AkImage from Akelos (Closer to ImageMagick in Rails) but got bunch of errors.

Any way i got article from sobbour website, but i am not satisfied with the code because the component automatically resize for big and thumb by 2 method directly, it will make bounced my hosting with trash image. And some lines were not realible any more with CakePHP, here is my modified Code (save it to /appName/controller/components/image.php)

class ImageComponent extends Object
{
var  $contentType =  array('image/jpg','image/bmp','image/jpeg','image/gif','image/png','image/pjpg','image/pbmp','image/pjpeg','image/ppng','image/pgif');
function  upload_image_and_thumbnail($fileData,$size,$subFolder,$prefix) {
if  (strlen($fileData['name'])>4)
 {
$error =  0;
$destFolder =  WWW_ROOT.$subFolder;
$realFileName  = $fileData['name'];
if(!is_dir($destFolder))  mkdir($destFolder,true);
  $filetype = $this->getFileExtension($fileData['name']);
$filetype  = strtolower($filetype);
if(!in_array($fileData['type'],$this->contentType)){
return false;exit();
}
else if($fileData['size'] > 700000 ){
return false;exit();
}
else
{
$imgsize =  GetImageSize($fileData['tmp_name']);
}
 if  (is_uploaded_file($fileData['tmp_name']))
 {
if  (!copy($fileData['tmp_name'],$destFolder.'/'.$realFileName ))
{
 return false;
exit();
}
else  {
  $this->resize_img($destFolder.'/'.$realFileName, $size,  $destFolder.'/'.$prefix.$realFileName);
 unlink($destFolder.'/'.$realFileName);
 }
 }
return  $fileData;
}
}
function delete_image($filename)
{
unlink($filename);
}
function  resize_img($tempFile, $size, $newFile)
{
$filetype =  $this->getFileExtension($tempFile);
$filetype =  strtolower($filetype);
switch($filetype) {
case "jpeg":
case "jpg":
 $img_src  = imagecreatefromjpeg($tempFile);
 break;
case "gif":
$img_src = imagecreatefromgif  ($tempFile);
break;
case "png":
$img_src = imagecreatefrompng  ($tempFile);
 case "bmp":
$img_src = imagecreatefromwbmp  ($tempFile);
break;
}
$true_width  = imagesx($img_src);
$true_height = imagesy($img_src);

$size = explode('x',strtolower($size));
if  ($true_width>=$true_height)
{
 $width=$size[0];
 $height =  ($width/$true_width)*$true_height;
}
else
{
 $height=$size[1];
 $width =  ($height/$true_height)*$true_width;
}
$img_des =  imagecreatetruecolor($width,$height);
imagecopyresampled  ($img_des, $img_src, 0, 0, 0, 0, $width, $height, $true_width,  $true_height);
// Save the resized image
switch($filetype)
{
 case "jpeg":
 case "jpg":
 imagejpeg($img_des,$newFile,80);
 break;
 case "gif":
 imagegif($img_des,$newFile,80);
break;
case  "png":
imagepng($img_des,$newFile,80);
case "bmp":
imagewbmp($img_des,$newFile,80);
break;
}
}
function  getFileExtension($str)
{
$i  = strrpos($str,".");
if (!$i) { return ""; }
$l =  strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
}


class  ImageComponent extends Object

{

var  $contentType =  array('image/jpg','image/bmp','image/jpeg','image/gif','image/png','image/pjpg','image/pbmp','image/pjpeg','image/ppng','image/pgif');

function  upload_image_and_thumbnail($fileData,$size,$subFolder,$prefix) {

if  (strlen($fileData['name'])>4)

 {

$error = 0;

$destFolder = WWW_ROOT.$subFolder;

$realFileName = $fileData['name'];

if(!is_dir($destFolder))  mkdir($destFolder,true);

 $filetype =  $this->getFileExtension($fileData['name']);

$filetype  = strtolower($filetype);

if(!in_array($fileData['type'],$this->contentType)){

return false;exit();

}

else if($fileData['size'] >  700000 ){

return  false;exit();

}

else

{

$imgsize =  GetImageSize($fileData['tmp_name']);

}

 if  (is_uploaded_file($fileData['tmp_name']))

 {

if  (!copy($fileData['tmp_name'],$destFolder.'/'.$realFileName ))

{

 return false;

exit();

}

else  {

  $this->resize_img($destFolder.'/'.$realFileName, $size,  $destFolder.'/'.$prefix.$realFileName);

  unlink($destFolder.'/'.$realFileName);

 }

 }

return $fileData;

}

}

function  delete_image($filename)

{

unlink($filename);

}

function  resize_img($tempFile, $size, $newFile)

{

$filetype =  $this->getFileExtension($tempFile);

$filetype =  strtolower($filetype);

switch($filetype) {

case "jpeg":

case "jpg":

 $img_src  = imagecreatefromjpeg($tempFile);

 break;

case "gif":

$img_src = imagecreatefromgif  ($tempFile);

break;

case "png":

$img_src = imagecreatefrompng  ($tempFile);

  case "bmp":

$img_src  = imagecreatefromwbmp ($tempFile);

break;

}

$true_width  = imagesx($img_src);

$true_height = imagesy($img_src);



$size =  explode('x',strtolower($size));

if  ($true_width>=$true_height)

{

 $width=$size[0];

 $height =  ($width/$true_width)*$true_height;

}

else

{

 $height=$size[1];

 $width =  ($height/$true_height)*$true_width;

}

$img_des =  imagecreatetruecolor($width,$height);

imagecopyresampled  ($img_des, $img_src, 0, 0, 0, 0, $width, $height, $true_width,  $true_height);

// Save the resized image

switch($filetype)

{

 case "jpeg":

 case "jpg":

 imagejpeg($img_des,$newFile,80);

 break;

 case "gif":

 imagegif($img_des,$newFile,80);

break;

case  "png":

imagepng($img_des,$newFile,80);

case  "bmp":

imagewbmp($img_des,$newFile,80);

break;

}

}

function  getFileExtension($str)

{

$i = strrpos($str,".");

if  (!$i) { return ""; }

$l = strlen($str) - $i;

$ext  = substr($str,$i+1,$l);

return $ext;

}

}

And in your class instance method , run this line

<?php
class DeJavu extends Appcontroller {
var $components = array("Image");
function add(){
....any code....
$this->Image->upload_image_and_thumbnail($this->data['Webinfo']['file'],'150x150','img','logo_');
....any code....
}
}
?>

now I am happy to see my app can resize image without annoying script any more. Good Luck for you too.

SharedObject in Sever Using NetConnection or by Remote

A few days ago i have problem how to implement my live streaming using SharedObject in Red5 because usually SharedObject, as i know, only good implementable for local only (like getting or store cookies), before implemented to my live streaming application, i created simple chat application to remote SharedObject :

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="creationComplete()">
<mx:Script source="streaming.as"/>
<mx:TextInput x="10" y="10" id="rtmpUrl" text="your rtmp address"/>
<mx:Button x="216" y="10" id="connectBtn"/>
<mx:TextInput x="10" y="269" id="enterMsg" />
<mx:TextArea x="10" y="40" height="221" id="msgBoard" width="222" />
<mx:Button x="178" y="269" id="sendBtn"/>
</mx:Application>

And now let create streaming.as script :
import flash.events.MouseEvent;
import flash.events.NetStatusEvent;
import flash.events.SyncEvent;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.SharedObject;

import mx.controls.Alert;

public var NetCont:NetConnection;
public var NetStrem:NetStream
public var SharObj:SharedObject;

public function creationComplete():void{
connectBtn.label = "Connect";
connectBtn.addEventListener(MouseEvent.CLICK, ConnectServer);

sendBtn.label = "Send";
sendBtn.addEventListener(MouseEvent.CLICK, SendChat);
}

public function ConnectServer(event:MouseEvent):void{
NetCont = new NetConnection();
NetCont.client = new NetConnectionClient;
NetCont.connect(rtmpUrl.text);
NetCont.addEventListener(NetStatusEvent.NET_STATUS, createSharedObject);
}

public function createSharedObject(event:NetStatusEvent):void{

if(NetCont.connected){
SharObj = SharedObject.getRemote("SampleMessage",NetCont.uri,false,false);
SharObj.connect(NetCont);
SharObj.addEventListener(SyncEvent.SYNC, SharObjView);


}else{

Alert.show('Unable to Connect Internet or Rtmp Address');


}
}


public function SharObjView(event:SyncEvent):void{
msgBoard.htmlText += SharObj.data['SampleMessage']+"<br>";

}

public function SendChat(event:MouseEvent):void{
SharObj.setProperty("SampleMessage",enterMsg.text);
}

There are 2 optional for using SharedObject in ActionScript specially for flex SharedObject.getLocal() method or the SharedObject.getRemote()

What we use for internet connection is using getRemote. And here is code for next connection client :
package
{
public class NetConnectionClient
{
public function NetConnectionClient()
{
}
public function onBWDone(... rest):void
{

}
public function onBWCheck(... rest):uint
{
//have to return something, so returning anything :)
return 0;
}

public function onMetaData(info:Object):void {
trace("metadata: duration=" + info.duration + " width=" + info.width + " height=" + info.height + " framerate=" + info.framerate);
}
}
}

Anti Spam Email For Your Rails Page with Javascript

In your view : <%= js_antispam_email_link('username@domain.com') %>


Code for your helper


# Takes in an email address and (optionally) anchor text,

# its purpose is to obfuscate email addresses so spiders and

# spammers can't harvest them.

def js_antispam_email_link(email, linktext=email)

user, domain = email.split('@')

user = html_obfuscate(user)

domain = html_obfuscate(domain)

# if linktext wasn't specified, throw encoded email address builder into js document.write statement

linktext = "'+'#{user}'+'@'+'#{domain}'+'" if linktext == email

rot13_encoded_email = rot13(email) # obfuscate email address as rot13

out = "#{linktext}&lt;br/&gt;&lt;small&gt;#{user}(at)#{domain}&lt;/small&gt;\n" # js disabled browsers see this

out += "// <![CDATA[

\n"

out += " \n"

out += " string = '#{rot13_encoded_email}'.replace(/[a-zA-Z]/g, function(c){ return String.fromCharCode((c = (c = c.charCodeAt(0) + 13) ? c : c - 26);});\n"

out += " document.write('#{linktext}'); \n"

out += " //\n"

out += "

// -->

// ]]>\n"

return out

end


private

# Rot13 encodes a string

def rot13(string)

string.tr "A-Za-z", "N-ZA-Mn-za-m"

end


# HTML encodes ASCII chars a-z, useful for obfuscating

# an email address from spiders and spammers

def html_obfuscate(string)

output_array = []

lower = %w(a b c d e f g h i j k l m n o p q r s t u v w x y z)

upper = %w(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)

char_array = string.split('')

char_array.each do |char|

output = lower.index(char) + 97 if lower.include?(char)

output = upper.index(char) + 65 if upper.include?(char)

if output

output_array << "&##{output};"

else

output_array << char

end

end

return output_array.join

end

Move To Word Press

I Recently Move my Blog To Wordpress --> inobject.wordpress.com

Track Total Coverage of Your Test Unit Code with RCOV

Hi All :

I just want share my testing with Ruby coverage code or Rcov. It is fun (for me, dont know for others) playing with Rcov report, i think it is like bugs tracking but i dont know other people called it or maybe it is like tool to coverage test your application codes.

First think you have to do is installing the gem :

gem install rcov

and then write simple code to run it as rake then save it in your_app/lib/tasks :

require 'rcov/rcovtask'

namespace :test do
namespace :coverage do

desc "Delete aggregate coverage data."

task(:clean) { rm_f "coverage.data" }
end

desc 'Aggregate code coverage for unit, functional and integration tests'

task :coverage => "test:coverage:clean"

%w[unit functional integration].each do |target|

namespace :coverage do

Rcov::RcovTask.new(target) do |t|
t.libs << "test"
t.test_files = FileList["test/#{target}/*_test.rb"]
t.output_dir = File.dirname(__FILE__)+"/report_rcov/#{target}"
t.verbose = true
t.rcov_opts << '--rails --aggregate coverage.data'
end
end

task :coverage => "test:coverage:#{target}"

end

system(" \"C:/Program Files/Mozilla Firefox/firefox.exe\" " +
"file:///"+File.dirname(__FILE__)+"/report_rcov/unit/index.html")

end


Absolutly i am using windows if you are using another OS not windows you could change the 4th line from bottom to :

system(open File.dirname(__FILE__)+"/report_rcov/unit/index.html")


Open your shell or CMD then execute rake test:coverage or open rake -T

rake test:coverage # Aggregate code coverage for unit,...
rake test:coverage:clean # Delete aggregate coverage data.
rake test:coverage:clobber_functional # Remove rcov products for functional
rake test:coverage:clobber_integration # Remove rcov products for integration
rake test:coverage:clobber_unit # Remove rcov products for unit
rake test:coverage:functional # Analyze code coverage with tests ...
rake test:coverage:integration # Analyze code coverage with tests ...
rake test:coverage:unit # Analyze code coverage with tests ...



Here I attached sample report from rcov. I hope this written can be useful for you gentleman and ladies.

 
powered by Blogger