Saturday, December 31, 2011

PDF Merge

PDF Merge

If you have more than one PDF files and need to merge them into a single file.
Then this utility will help you.

PDF Merger
PDF Merger
















You can download it here.


Thursday, December 15, 2011

Latest Posts

View here my latest posts.

Want to look my latest Posts? just Click here

Monday, November 21, 2011

Jooble job search engine

Jooble is a job search engine and it operates in 48+ countries around the world and we continue to expand its services. The work of our site is very simple. With the help of Jooble you may search jobs across the whole India. We aggregated the most of the job boards in India and simplify the process of job searching.
Here is the list of countries we work in:
Argentina, Australia, Austria, Belgium, Belarus, Brazil, Canada, Chilie, China Colombia, Czech Republic, Denmark, Spain, Finland, France, Germany, Greece, Hong Kong, Hungary, Italy, India, Indonesia, Ireland, Japan, Kazakhstan, Mexico, Netherlands, New Zeland, Nigeria, Norway, Pakistan, Peru, Poland, Portugal, Romania, Russia , South Korea, Sweden, Switzerland, Taiwan, Thailand, Turkey , Venezuela, Ukraine, United Kingdom, United States

Just Jooble to find your dream job in just few clicks!

Wednesday, June 29, 2011

How to get clipboard data from webpage.

How to get clipboard data from webpage.
--------------------------------------------------------

Just put all the files(amitcert.crt, GetClipBoardData.html and GetClipBoardData.jar)
in the web directory.

After that open GetClipBoardData.html, it will ask for authentication, just
click on run button.




then try to copy any text and press GetClipBoardData button
you will find your copied text.


Download here full code









How to show place in Google map

How to show place in Google map
-----------------------------------

1) Create a table "latandlon" in Mysql/Oracle/Sqlserver/DB2 in which you feel easy.

CREATE TABLE latandlon (
  id int(11) NOT NULL auto_increment,
  lat decimal(10,6) NOT NULL default '0.000000',
  lon decimal(10,6) NOT NULL default '0.000000',
  address varchar(255) NOT NULL default '',
  PRIMARY KEY  (id)
);


2) feed the listed below data.
----------------------------------------------------------
id,     lat,            lon,            address
----------------------------------------------------------
1    23.402800    78.454100    Madhya Pradesh
2    26.280000    80.210000    Kanpur
3    31.122027    77.111664    Himanchal Pradesh
4    22.533000    88.367000    Kolkata
5    28.350000    77.120000    Delhi
6    17.230000    78.290000    Hyderabad
----------------------------------------------------------





3) put youe google map key in the index.jsp.


 <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<%
// How to show place in google map
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">  
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
<script src="http://maps.google.com/maps?file=api&v=2&key=YOURKEYHERE" type="text/javascript">
</script>
<body>
<p><strong>locations in India</strong></p>
<div id="map" style="width: 800px; height: 600px"></div>

<script type="text/javascript">
//<![CDATA[
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.addControl(new GScaleControl());
map.setCenter(new GLatLng(23.402800, 78.454100), 5, G_NORMAL_MAP);
function createMarker(point, number)
{
var marker = new GMarker(point);
var html = number;
GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(html);});
return marker;
};
<%
    String userName = "root";
    String password = "";
    String url = "jdbc:mysql://localhost:3306/test";
    try{
        String driver = "com.mysql.jdbc.Driver";
        Class.forName(driver).newInstance();
        Connection conn;
        conn = DriverManager.getConnection(url, "root","");
        Statement s = conn.createStatement ();
        s.executeQuery ("SELECT *from latandlon");
        ResultSet rs = s.getResultSet ();
        int count = 0;
        while (rs.next ()) {
            String lat = rs.getString ("lat");
            String lon = rs.getString ("lon");
            String address=rs.getString ("address");
            out.print("var point = new GLatLng("+lat+","+lon+");\n");
            out.print("var marker = createMarker(point, '"+address+"');\n");
            out.print("map.addOverlay(marker);\n");
            out.print("\n");
        }
        rs.close ();
        s.close ();
    }
    catch(Exception ee){
        System.out.println(ee.toString());  
    }
%>
//]]>
</script>
</body>
</html>

4) change the database connection string in the index.jsp page, coz I have used MySql.







Transform XML file in HTML with XSLT in JSP

Transform XML file in HTML with XSLT in JSP

How to transform xml file in html with xslt in J2EE, JSP
----------------------------------------------------------
I have used SAXON XSLT and XQuery Processor library http://saxon.sourceforge.net/
1)saxon9ee.jar 2)saxon9ee-qc.jar 3)saxon9-sql.jar

The Latest version you can download from http://prdownloads.sourceforge.net/saxon/saxon6-5-5.zip
or from here http://sourceforge.net/projects/saxon/

There are 3 xml files for testing purpose
1) result.xml having result information.
2) result_notfound.xml having no any result information.
3) TestSearchResult.xml having partial result information.

you can change xml file to see different html result.

In the xsl file I have used some basic function like count(),position(),and images also showing.

*To open this project use MyEclipse6.0 or later.

Download here xml to html entire code





Add new row dynamically in JTable

This is Java code allow to you add a new row in JTable.
when you press enter then a new row automatically inserted and you can make more entry.



See here full code

Wednesday, June 15, 2011

Delete recent file automatically

Recent files Terminator

Windows Recent document is good for us, by this we can open recent document immediately. but in the case of privacy it is not good. because someone can open/see your Important document.
To prevent this you can clear the recent document list. But what will happen when someone immediately came to near you and try to use your system,in this case you have not sufficient time to clear recent document. There are many software are available that clear recent file but they clear the recent file on system start-up or shut down not immediately! The above problem is really interesting.
okay, so I have created this small and powerful utility.
it will remove the recent file immediately and intervals when you open it.
It will help you to protect to see your important document from Other user.

To run this utility you need to install dot net framework 3.5

Download here

Export to excel with preserve starting(Leading) zeros values in ASP Dot Net.

Export to excel with preserve starting(Leading) zeros values in ASP Dot Net.

In my office colleague was facing an interesting problem.
Sql sever data was listed below:
-------------------------------------------
ID EmpID EmpName Salary
1 000001 aa 1111111
2 000002 bb 2222222
3 000003 cc 3333333
4 000004 dd 4444444
5 000005 ee 5555555
-----------------------------------------
Column EmpID was varchar type, he was just trying export these data to MS-Excel,
so first show the data by GridView and then export it as a excel file.
But while opening excel file "000001" was showing as "1" and "000002" was showing as "2" and so on. the situation was "00000" were removed as below.
-------------------------------------------
ID EmpID EmpName Salary
1 1 aa 1111111
2 2 bb 2222222
3 3 cc 3333333
4 4 dd 4444444
5 5 ee 5555555
6 6 ff 6666666
----------------------------------------
He just requested me to help and I helped him.I've searched these problem in Microsoft site(MSDN) and found the solution
and implemented it. now he is getting right data in excel.


Download code here

Tuesday, June 14, 2011

Notice Use of undefined constant - assumed in on line error

Notice: Use of undefined constant  - assumed '_' in .....php on line nn

This is the error which many PHP programmer face in coding.
The most important fixes are listed below:
1- you have not declared contant, so declared it
2- use single or double quotes in constant for ex: define('MYCONST', "abc")
3- many  use short open tag "<?" so enable it or user "<?php".





Monday, June 6, 2011

Set focus in next control on enter in PHP,ASP.NET,JSP,SERVLETS,jQuery

Set focus in next control on enter in PHP,ASP.NET,JSP,SERVLETS.


Download latest jQuery and apply listed below code in your web page.


<script language="javascript" src="../js/jquery-1.6.js" type="text/javascript"></script>
<input type="text" name="t1" id="t1" onkeyup="javascript: if(setFocusNext(event)) $('#t2').focus();" />
<br/>
<input type="text" name="t2" id="t2" onkeyup="javascript: if(setFocusNext(event)) $('#t3').focus();" />
<br/>
<input type="text" name="t3" id="t3" />
<script type="text/javascript">
    function setFocusNext(e){
    var cd=0;
    if(window.event) {
        cd = e.keyCode;
    } else if(e.which) {
        cd = e.which;
    }
    if(cd==13) {
        return true;
    } else {
        return false;
    }
}
</script>

Friday, June 3, 2011

Images To Text/Extract text from images (OCR) in dot net

Images To Text / Extract text from images (OCR) in dot net


Here is the application that will takes the directory, where all images
are stored and convert those images to text by one click.

link for that application

Thursday, June 2, 2011

Sending email in PHP from Gmail

Sending email in PHP from Gmail

For sending email in PHP by Gmail id, I have used phpmailer class.
Note that php_openssl must be un-commented in the php.ini file.
In phpMailer directory open "class.phpgmailer.php"  and change the line as listed below:
var $Host        = "ssl://smtp.gmail.com";
var $Port        = 465;


Put listed below code in php file from where you want to send email.
require_once('phpgmailer/class.phpgmailer.php');
$mailToClient=new PHPGMailer();
$mailToClient->IsHTML(true);
$mailToClient->Username='full-gmail-address';//'a@gmail.com';  
$mailToClient->Password='gmail-password-here';//amitabc123  
$mailToClient->From='full-gmail-address';//a@gmail.com';  
$mailToClient->FromName='Amit';
$mailToClient->Subject='YOUR-SUBJECT';//a@gmail.com
$mailToClient->AddAddress('recipient email address here');
$mailToClient->Body='Hey, Here is Amit!';
$mailToClient->Send();

Wednesday, June 1, 2011

Reading XML in jQuery/Generate sitemap in jQuery

Reading XML in jQuery/Generate sitemap in jQuery

Here listed below code is showing that how can you can generate site map with jQuery.
just copy the sites.php file's matter in your site's  sites.php and copy sites.html file's matter
in your  sites.html file.



 sites.php

< ? php
header( 'Content-type: text/xml' );
$xmlData='';
echo '';
$xmlData .= ' < sites >';
$xmlData.='   < site id="0">';
$xmlData.="     < ttitle >Amit's Blog < /ttitle >";
$xmlData.='    < url >http://amitkgaur.blogspot.com/< / url >';
$xmlData.='     < desc >';
$xmlData.='       < brief >Find interesting stuff in Java, PHP and Dot Net.< / brief >';
$xmlData.='       < long >This site is for Humans, smart Primates and Dolphins only (oh and ALIENS).';
$xmlData.='     < /desc >';
$xmlData.='   < / site >';
$xmlData.='   < site id="2" >';
$xmlData.='     < ttitle >Auto Resume Broken File Upload Applet With Progress Bar< /ttitle >';
$xmlData.='    < url >http://amitkgaur.blogspot.com/2010/10/file-upload-applet-with-auto-resume.html< /url >';
$xmlData.='     < desc >';
$xmlData.='       < brief >Upload unlimited GBs file without fear of internet connection break.< / brief >';
$xmlData.='       < long >I have created this Java Auto Resume Broken and Progress Bar File Uploader Applet.< / long >';
$xmlData.='     < / desc >';
$xmlData.='   < / site >';
$xmlData.='   < site id="3" >';
$xmlData.='     < ttitle >Desktop Screen Recorder< / ttitle > ';
$xmlData.='    < url >http://amitkgaur.blogspot.com/2010/09/desktop-screen-recorder.html< /url >';
$xmlData.='     < desc >';
$xmlData.='       < brief >This Screen Recorder will record your screen and generate .MOV file,
I have created it in Java Swing Framework.< / brief >';
$xmlData.='       < long >This Screen Recorder will record your screen and generate .MOV file,
I have created it in Java Swing Framework.
I recommend VLC player to play this file.< / long >';
$xmlData.='     < / desc >';
$xmlData.='   < / site >';
$xmlData.=' < / sites >';
echo $xmlData;
? >



sites.html

   < script type="text/javascript" src="jquery-1.6.js" > < / script >
     < script >
         $(document).ready(function(){
            $.ajax({
                type: "POST",
                url: "sites.php",
                dataType: "xml",
                success: function(xml) {
                    $(xml).find('site').each(function(){
                        var id = $(this).attr('id');
                        var ttitle = $(this).find('ttitle').text();
                        var url = $(this).find('url').text();
                    $('
').html(''+ttitle+'').appendTo('#siteMap');
                        $(this).find('desc').each(function(){
                            var brief = $(this).find('brief').text();
                            var long = $(this).find('long').text();
                            $('
').html(brief).appendTo('#link_'+id);
                            $('
').html(long).appendTo('#link_'+id);
                        });
                    });
                }
            });
        });
    
    <div id="siteMap" >
         Sitemap with jQuery
     </div>

       

        



    


Saturday, May 14, 2011

Use proxy server in PHP

How to use proxy server in PHP.

<?php
// First get the Free proxy list from here
// http://hidemyass.com/proxy-list/search-284460

set_time_limit(0) ;
$t1=time();
$urltopost = "http://amitkgaur.blogspot.com/";

// $urltopost = http://www.xyz.com/t3resultpage.aspx?type=p=test1&q=test2&rid=7851
// $datatopost = array (
//  "firstname" => "Amit",
// "lastname" => "Gaur",
// "blog" => "http://amitkgaur.blogspot.com/",
// );

 $crl = curl_init ($urltopost);
 curl_setopt ($crl, CURLOPT_POST, true);
 curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($crl, CURLOPT_PROXY, "115.248.234.254:3128");
 curl_setopt($crl, CURLOPT_PROXYPORT, 3128); 
 //curl_setopt ($crl, CURLOPT_POSTFIELDS, $datatopost);
 curl_setopt ($crl, CURLOPT_RETURNTRANSFER, true);
 $ans = curl_exec ($crl);
 $t2=time();
 $lapsed=$t2-$t1;
 echo "<br/>Total time taken" . $lapsed;
 echo $ans;
?>

Thursday, April 28, 2011

IP to Country State City Latitude Longitude

IP to Country State City Latitude Longitude

just wait for the link...

Wednesday, March 30, 2011

Show MySql database table's column name with type

Show MySql database table's column name with type.

Situation where you want to work with mysql database's table in php
for ex: showing records etc  and you don’t have the access information
of mysql database and don't know the column names.
You only are having FTP Information. 
In this tough condition you can do the your job.
Here is the code that will show maysql database table’s column full information.

< ? php
    $host = "Server-IP-Here";
    $user = "Database-User-Id-Here";
    $password = "Database-User-Ids-Password-Here";
    $database = "Database-Name";
    $serverLink = mysql_connect($host,$user,$password);
    mysql_select_db($database,$serverLink);
    //$ssql = "SHOW COLUMNS FROM Table-Name-Here";
    $ssql = "SHOW COLUMNS FROM office_mast";
    $rs = mysql_query($ssql);
    while($col = mysql_fetch_array($rs, MYSQL_BOTH)) {
        print_r($col);
        echo "
";
    }
    mysql_free_result($rs);
    mysql_close($serverLink);
? >

Sunday, March 20, 2011

Read Gmail email and save attachement in Java

Read GMAIL Email and save attachment in JAVA.

set class path of these jara files mail.jar and activation.jar
and run these piece of code.



import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class GmailMailAttach {
    public static void main (String args[]) throws Exception {
        String host = "pop.gmail.com";
        String username = "amitt800"; //Put here Gmail Username without @ sign
        String password = "123456"; // put here Gmail password
        Session session = Session.getInstance(new Properties(), null);
        Store store = session.getStore("pop3s");
        store.connect(host, username, password);
        Folder folder = store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        Message message[] = folder.getMessages();
       Enumeration headers = message[i].getAllHeaders();
       while (headers.hasMoreElements()) {
             Header h = (Header) headers.nextElement();
             System.out.println(h.getName() + ": " + h.getValue());
       }

        for(int i=0, n=message.length; i++) {
            System.out.println(i + ": " + message[i].getFrom()[0]+ "\t" + message[i].getSubject());
            System.out.println("Want to get the content? [Y to read/Q to end]");
            String ans = reader.readLine();
            ans=ans.toLowerCase();
            if ("y".equals(ans)) {
                Object content = message[i].getContent();
                if (content instanceof Multipart) {
                    handleMultipart((Multipart)content);
                }
                else {
                    handlePart(message[i]);
                }
            }
            else if ("q".equals(ans)) {
                break;
            }
        }
        folder.close(false);
        store.close();
    }
    public static void handleMultipart(Multipart multipart) throws MessagingException, IOException {
        for (int i=0, n=multipart.getCount(); i
            handlePart(multipart.getBodyPart(i));
        }
      }
    public static void handlePart(Part part)  throws MessagingException, IOException {
        String dposition = part.getDisposition();
        String cType = part.getContentType();
        if (dposition == null) {
            System.out.println("Null: "  + cType);
            if ((cType.length() >= 10) && (cType.toLowerCase().substring(0, 10).equals("text/plain"))) {
                part.writeTo(System.out);
            }
            else {
                System.out.println("Other body: " + cType);
                part.writeTo(System.out);
            }
        }
        else if (dposition.equalsIgnoreCase(Part.ATTACHMENT)) {
            System.out.println("Attachment: " + part.getFileName() + " : " + cType);
            saveFile(part.getFileName(), part.getInputStream());
        }
        else if (dposition.equalsIgnoreCase(Part.INLINE)) {
            System.out.println("Inline: " + part.getFileName() +  " : " + cType);
            saveFile(part.getFileName(), part.getInputStream());
        }
        else { 
            System.out.println("Other: " + dposition);
        }
    }
   
    public static void saveFile(String filename,InputStream input) throws IOException {
        if (filename == null) {
            filename = File.createTempFile("MailAttacheFile", ".out").getName();
        }
        System.out.println("downloading attachment...");
        File file = new File(filename);
        for (int i=0; file.exists(); i++) {
            file = new File(filename+i);
        }
        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        BufferedInputStream bis = new BufferedInputStream(input);
        int fByte;
        while ((fByte = bis.read()) != -1) {
            bos.write(fByte);
            }
        bos.flush();
        bos.close();
        bis.close();
        System.out.println("done attachment...");
    }
}

Tuesday, March 15, 2011

Set timezone in PHP

Set timezone in PHP


date_default_timezone_set('America/Los_Angeles');
// Asia/Calcutta
$format = 'Y-m-d H:i:s A'
echo date($format);

Blink text in jQuery

Blinking text in jQuery

< div id=""msg" > your message here< / div >
< script language = " javascript " >
    function setFade() {
        $( "#msg").fadeOut(1000, function () {
            $("#msg").fadeIn();
        });
        }
        setInterval("setFade();",100);
< / script >

Wednesday, February 9, 2011

Post entire form and return JSON data from Asp.net C#

Here is the entire code that will post entire asp.net
form to the target page. The target page will receive
the post data and return the result in the format of JSON data.

Here are the two things one is it will send entire form data,
so you not need to mention every control name with parameter in Ajax.
second one is the target page which receive the data, is return output as
JSON Format.

First you need to download the latest jquery from the jquery site and then copy and
paste the below code and run it.



[1] jQAjaxPostEntireForm.aspx
------------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="jQAjaxPostEntireForm.aspx.cs" Inherits="jQAjaxPostEntireForm" 

enableViewStateMac="False" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Post entire form and return JSON data from Asp.net C#</title>
    <script type="text/javascript" src="js/jquery-1.6.js"></script>
</head>
<body>
    <form name="emailForm" id="emailForm" runat="server">
    <div>
        <p>Name:<br /><asp:TextBox ID="nName" runat="server"></asp:TextBox>
        </p>
        <p>E-mail:<br /><asp:TextBox ID="email" runat="server"></asp:TextBox>
        </p>
        <p><asp:Button ID="Button1" runat="server" Text="Submit" OnClientClick="return doSubmit();" />
        </p>
        <div id="msg"></div>
    </div>
    </form>
</body>

<script type="text/javascript">
    function doSubmit() {
        dataString = $("#emailForm").serialize();
        $.ajax({
            type: "POST",
            url: "jQAjaxPostEntireFormProcess.aspx",
            data: dataString,
            dataType: "json",
            timeout: 5000,
            error: function (xhr, err) {
                $("#msg").html(xhr.responseText + xhr.readyState + xhr.status);
            },
            success: function (data) {
                $("#msg").html(data.yourName + " your Email is :" + data.yourEmail);
            }
        });
        return false;
    }
</script>
</html>
=====================================================
[2] jQAjaxPostEntireForm.aspx.cs
-------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class jQAjaxPostEntireForm : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

=====================================================
[3] jQAjaxPostEntireFormProcess.aspx
-------------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="jQAjaxPostEntireFormProcess.aspx.cs"

Inherits="jQAjaxPostEntireFormProcess"  enableViewStateMac="False" %>

=====================================================
[4] jQAjaxPostEntireFormProcess.aspx.cs
--------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;
public partial class jQAjaxPostEntireFormProcess : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       string str;
       JavaScriptSerializer js = new JavaScriptSerializer();
       String yourName=Request.Form["nName"];
       String yourEmail=Request.Form["email"];
       str = "{\"yourName\":\"" + yourName + "\",\"yourEmail\":\"" + yourEmail + "\"}";
       // It is better to use class for JSON, but I have not used it here.
       // because I want just return only two datas.              
       //mailInfo p1 = new mailInfo();
       //p1.yourName = yourName;
       //p1.yourEmail = yourEmail;
       //str = js.Serialize(p1);
       Response.Write(str);
      
   }
}
public class mailInfo
{
    public string yourName, yourEmail;
}

Wednesday, January 12, 2011

Image resize without distortion and keeping proportions

Image resize without distortion and keeping proportions.



Image distortion is the normal problem with the image resize in
any programming language. You need to have good knowledge of math to
resizing the image.
I have implemented image resize code without distortion in PHP.
You can easily convert it in the any other programming language
for ex: ASP.Net, JSP etc:

Here is the listed below code:
====================================

img_resize.php

$filename = "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiQOT3CzejzFpMcWAqDQekKgdvDT8f4Ot1gFRIG3UDWN8N8y7kIMAagI85rho803ugEzu5IgQDK9k8FgDxsjKe8xgJ8zpaW8JaejckiKU3tnhYy48q0m2eavUhP9yn9x8cU-t7e4YPepPg/s1600/auto-resume-broken-uploader.jpg";
$nw = 170; // new width
$nh = 128; // new height
header('Content-type: image/jpeg');
list($width, $height) = getimagesize($filename);
if($width<= $nw) {
   $nw=$width;
}
$newHeight = $height*$nw/$width; // calculate new height here
if($newHeight > $nh) {
   $nw = $width*$nh/$height;
   $newHeight=$nh;
}
$image_s = imagecreatetruecolor($nw,$newHeight);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_s, $image, 0, 0, 0, 0, $nw,$newHeight,$width,$height);
imagejpeg($image_p, null, 100);   


use it as listed below:
<img src="img_resize.php" />

Note that you can also make the parameter for height and width.







Saturday, January 1, 2011

Better AlertDialog box in Android

Better AlertDialog box in Android



package com.mytest.android;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MyTestActivity extends Activity {
    ProgressDialog progressDialog;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        progressDialog = new ProgressDialog(this);
        Button buttonClickMe = (Button)findViewById(R.id.button1);
        buttonClickMe.setOnClickListener(new OnClickListener() {
        @Override
            public void onClick(View arg0) {
                //progressDialog.setMessage("Please wait ... ");
                //progressDialog.show();
                // do stuff here......
                // to cancel progressDialog box
                //progressDialog.cancel();
                // finally show dialog box here
                MyAlert.displayAlert(MyTestActivity.this , "Notification", "You have pressed on me!!!", null, "Ok");
            }
        });
    }
  
}




=================================================


package com.mytest.android;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
public class MyAlert {
    public static void displayAlert(Context cntx ,String title,String message, final String NegButton,final String posButton) {
        AlertDialog.Builder alertBuilder = new Builder( cntx);
        alertBuilder.setTitle(title);
        alertBuilder.setMessage(message);
        if(NegButton != null) {
            alertBuilder.setNegativeButton(NegButton,new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) { }
            });
        }
       
        if (posButton != null) {
            alertBuilder.setPositiveButton(posButton,new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            });
        }
        AlertDialog alert = alertBuilder.create();
        alert.show();
    }
}




Android App