Friday, October 9, 2015

PNG to JPG - Conversion and Compression - PHP






Code is below:

<?php

if(isset($_POST['submit'])){

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["myfile"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

move_uploaded_file($_FILES["myfile"]["tmp_name"], $target_file);

$filePath = './uploads/'.basename( $_FILES["myfile"]["name"]);
$image = imagecreatefrompng($filePath);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 50; // 0 = worst / smaller file, 100 = better / bigger file

$image_name = str_replace('.png','',$filePath);

imagejpeg($bg, $image_name . ".jpg", $quality);

imagedestroy($bg);


}


?>




<form action="" enctype="multipart/form-data" method="post">
         <input type="file" name="myfile" value="" >
         <input type="submit" name="submit" >
</form>

No comments:

Post a Comment