Selasa, Maret 29, 2011

PHP : Auto Resize Image on Upload

Case : you want to resize image on upload
Solution : PHP imagecopyresampled
Script :

if ($_SESSION[username_administrasi] != "" && $_POST[submit] == "Simpan") {
$cek = cek("select * from ktp where no_ktp = '$no_ktp' and npwp = '$npwp' ");
if ($cek > 0) {
alert("Data sudah ada !");
loncat("../index.php");
} else {
$tmp_filename = $_FILES[file1][tmp_name];
$filename = $_FILES[file1][name];
$file = explode(".",$filename);
$nama_file = $file[0];
echo $nama_file;
list($old_width, $old_height, $type, $attr) = getimagesize($tmp_filename);
if ($type == 1 || $type == 2 || $type == 3) {
if (($_FILES["file1"]["size"]/1024) > 250) {
if ($type == 1) {
$new_image = imagecreatefromgif($tmp_filename);
} else if ($type == 2) {
$new_image = imagecreatefromjpeg($tmp_filename);
} else if ($type == 3) {
$new_image = imagecreatefrompng($tmp_filename);
}

echo "
width asli = ".$old_width;
echo "
height asli = ".$old_height;
$new_width = 800;

if ($old_width > $old_height) {
$percentage = ($new_width / $old_width);
} else {
$percentage = ($new_width / $old_height);
}

$new_width = round($old_width * $percentage);
$new_height = round($old_height * $percentage);

echo "
width resize = ".$new_width;
echo "
height resize = ".$new_height;

echo "
".$_FILES[file1][type];
echo "
".$_FILES[file1][size];


if (function_exists(imagecreatetruecolor)){
$resized_img = imagecreatetruecolor($new_width,$new_height);
}else{
die("Error: Please make sure you have GD library ver 2+");
}

imagecopyresampled($resized_img, $new_image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);

if ($type == 1) {
imagegif($resized_img,"../images/uploaded/tumb_".$nama_file.".gif");
} else if ($type == 2) {
imagejpeg($resized_img,"../images/uploaded/tumb_".$nama_file.".jpg");
} else if ($type == 3) {
imagepng($resized_img,"../images/uploaded/tumb_".$new_image.".png");
}

$move = move_uploaded_file($_FILES['file1']['tmp_name'], '../images/uploaded/real_'.$filename);

ImageDestroy ($resized_img);
ImageDestroy ($new_image);

loncat("../index.php");
} else {

$move = move_uploaded_file($_FILES['file1']['tmp_name'], '../images/uploaded/real_'.$filename);

if ($move) {
alert("Upload sukses.");
} else {
alert("Upload gagal.");
}
loncat("../index.php");
}
} else {
alert(" Tipe file yang diijinkan : GIF, JPG, JPEG, PNG");
//loncat("../index.php");
}
}
}



Source : http://www.php.net/

2 comments:

lina@women's perspectives mengatakan...

I need this; but it's a long script...
Usually I do it manually by using ACDSee.

Fery Wardiyanto mengatakan...

setidaknya ada penjelasan ato comment di tiap baris gan. jadi si pembaca gak bingung. (saran aja sih) hehehehe..

nice share lah :D