I have this piece of code for uploading images. It makes thumbnails with PNG extension with level 9 compression, but the images do not look good. I want just -50% or little more compression of PNG with transparency.
$path_thumbs = "../pictures/thumbs/";
$path_big = "../pictures/";
$img_thumb_width = 140; //
$extlimit = "yes";
$limitedext = array(".gif",".jpg",".png",".jpeg",".bmp");
$file_type = $_FILES['image']['type'];
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
if(!is_uploaded_file($file_tmp)){
echo "choose file for upload!. <br>--return";
exit();
}
$ext = strrchr($file_name,'.');
$ext = strtolower($ext);
if (($extlimit == "yes") && (!in_array($ext,$limitedext))) {
echo "dissallowed! <br>--return";
exit();
}
$getExt = explode ('.', $file_name);
$file_ext = $getExt[count($getExt)-1];
$rand_name = md5(time());
$rand_name= rand(0,10000);
$ThumbWidth = $img_thumb_width;
if($file_size){
if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
$new_img = imagecreatefromjpeg($file_tmp);
}elseif($file_type == "image/x-png" || $file_type == "image/png"){
$new_img = imagecreatefrompng($file_tmp);
}elseif($file_type == "image/gif"){
$new_img = imagecreatefromgif($file_tmp);
}
list($width, $height) = getimagesize($file_tmp);
$imgratio = $width/$height;
if ($imgratio>1){
$newwidth = $ThumbWidth;
$newheight = $ThumbWidth/$imgratio;
}else{
$newheight = $ThumbWidth;
$newwidth = $ThumbWidth*$imgratio;
}
if (#function_exists(imagecreatetruecolor)){
$resized_img = imagecreatetruecolor($newwidth, $newheight);
}else{
die("Error: Please make sure you have GD library ver 2+");
}
imagecopyresized($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
ImagePng ($resized_img, "$path_thumbs/$rand_name.$file_ext,9");
ImageDestroy ($resized_img);
ImageDestroy ($new_img);
}
move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext");
For better better quality of the resized image, you should use imagecopyresampled instread of imagecopyresized.
For image transparency you should look at imagesavealpha.
To make it work, you need to enable it, before you resize the image and you also need to disable alpha blending. It's best, to put it just after imagecreatetruecolor.
$resized_img = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($resized_img, false);
imagesavealpha($resized_img, true);
As for the size, you have a typo in your code
ImagePng ($resized_img,"$path_thumbs/$rand_name.$file_ext,9");
should be
ImagePng ($resized_img, "$path_thumbs/$rand_name.$file_ext", 9);
you put your compression level parameter into the filename instead of the function.
And compression level here doesn't mean it will make your filesize much smaller. It's a tradeoff between speed and filesize.
There is a limit how much you can losslessly compress a file.
If filesize is a concern, you should compress it with lossy compression like JPEG.
I think (I did not verify) that you should use the function imagecopyresampled instead of imagecopyresize. I think imagecopyresampled has a higher quality. You might also want to start of by using imagecreatetruecolor
I got a form where the user is inserting some data and also uploading an image.
To deal with the image, I got the following code:
define("MAX_SIZE", "10000");
$errors = 0;
$image = $_FILES["fileField"]["name"];
$uploadedfile = $_FILES['fileField']['tmp_name'];
if($image){
$filename = stripslashes($_FILES['fileField']['name']);
$extension = strtolower(getExtension($filename));
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")){
echo ' Unknown Image extension ';
$errors = 1;
} else {
$newname = "$product_cn.$extension";
$size = filesize($_FILES['fileField']['tmp_name']);
if ($size > MAX_SIZE*1024){
echo "You have exceeded the size limit";
$errors = 1;
}
if($extension == "jpg" || $extension == "jpeg" ){
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
} else if($extension == "png"){
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
} else {
$src = imagecreatefromgif($uploadedfile);
}
list($width, $height) = getimagesize($uploadedfile);
$newwidth = 60;
$newheight = ($height/$width)*$newwidth;
$tmp = imagecreatetruecolor($newwidth, $newheight);
$newwidth1 = 25;
$newheight1 = ($height/$width)*$newwidth1;
$tmp1 = imagecreatetruecolor($newwidth1, $newheight1);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagecopyresampled($tmp1, $src, 0, 0, 0, 0, $newwidth1, $newheight1, $width, $height);
$filename = "../products_images/$newname";
$filename1 = "../products_images/thumbs/$newname";
imagejpeg($tmp, $filename, 100); // file name also indicates the folder where to save it to
imagejpeg($tmp1, $filename1, 100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
getExtension function:
function getExtension($str) {
$i = strrpos($str, ".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
I've wrote some notation in the code since I'm not really familiar with those functions.
For some reason, it doesn't work. When I'm going to the folder "product_images" or "product_images/thumbs", I can't find any image uploaded.
Any idea what's wrong with my code? There should be 60px width image, and 25px width image.
Note: Variables that you don't know where they were declared such as $product_cn were declared before that block of code which works prefectly fine (tested). If you still want a glance at it, feel free to ask for the code.
Here is another nice and easy solution:
$maxDim = 800;
$file_name = $_FILES['myFile']['tmp_name'];
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
$target_filename = $file_name;
$ratio = $width/$height;
if( $ratio > 1) {
$new_width = $maxDim;
$new_height = $maxDim/$ratio;
} else {
$new_width = $maxDim*$ratio;
$new_height = $maxDim;
}
$src = imagecreatefromstring( file_get_contents( $file_name ) );
$dst = imagecreatetruecolor( $new_width, $new_height );
imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
imagedestroy( $src );
imagepng( $dst, $target_filename ); // adjust format as needed
imagedestroy( $dst );
}
Reference: PHP resize image proportionally with max width or weight
Edit: Cleaned up and simplified the code a bit. Thanks #jan-mirus for your comment.
You can use this library to manipulate the image while uploading. http://www.verot.net/php_class_upload.htm
// This was my example that I used to automatically resize every inserted photo to 100 by 50 pixel and image format to jpeg hope this helps too
if($result){
$maxDimW = 100;
$maxDimH = 50;
list($width, $height, $type, $attr) = getimagesize( $_FILES['photo']['tmp_name'] );
if ( $width > $maxDimW || $height > $maxDimH ) {
$target_filename = $_FILES['photo']['tmp_name'];
$fn = $_FILES['photo']['tmp_name'];
$size = getimagesize( $fn );
$ratio = $size[0]/$size[1]; // width/height
if( $ratio > 1) {
$width = $maxDimW;
$height = $maxDimH/$ratio;
} else {
$width = $maxDimW*$ratio;
$height = $maxDimH;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor( $width, $height );
imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $size[0], $size[1] );
imagejpeg($dst, $target_filename); // adjust format as needed
}
move_uploaded_file($_FILES['pdf']['tmp_name'],"pdf/".$_FILES['pdf']['name']);
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data" id="something" class="uniForm">
<input name="new_image" id="new_image" size="30" type="file" class="fileUpload" />
<button name="submit" type="submit" class="submitButton">Upload Image</button>
</form>
<?php
if(isset($_POST['submit'])){
if (isset ($_FILES['new_image'])){
$imagename = $_FILES['new_image']['name'];
$source = $_FILES['new_image']['tmp_name'];
$target = "images/".$imagename;
$type=$_FILES["new_image"]["type"];
if($type=="image/jpeg" || $type=="image/jpg"){
move_uploaded_file($source, $target);
//orginal image making part
$imagepath = $imagename;
$save = "images/" . $imagepath; //This is the new file you saving
$file = "images/" . $imagepath; //This is the original file
list($width, $height) = getimagesize($file) ;
$modwidth = 1000;
$diff = $width / $modwidth;
$modheight = $height / $diff;
$tn = imagecreatetruecolor($modwidth, $modheight) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
echo "Large image: <img src='images/".$imagepath."'><br>";
imagejpeg($tn, $save, 100) ;
//thumbnail image making part
$save = "images/thumb/" . $imagepath; //This is the new file you saving
$file = "images/" . $imagepath; //This is the original file
list($width, $height) = getimagesize($file) ;
$modwidth = 150;
$diff = $width / $modwidth;
$modheight = $height / $diff;
$tn = imagecreatetruecolor($modwidth, $modheight) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
//echo "Thumbnail: <img src='images/sml_".$imagepath."'>";
imagejpeg($tn, $save, 100) ;
}
else{
echo "File is not image";
}
}
}
?>
Building onto answer from #zeusstl, for multiple images uploaded:
function img_resize()
{
$input = 'input-upload-img1'; // Name of input
$maxDim = 400;
foreach ($_FILES[$input]['tmp_name'] as $file_name){
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
$target_filename = $file_name;
$ratio = $width/$height;
if( $ratio > 1) {
$new_width = $maxDim;
$new_height = $maxDim/$ratio;
} else {
$new_width = $maxDim*$ratio;
$new_height = $maxDim;
}
$src = imagecreatefromstring( file_get_contents( $file_name ) );
$dst = imagecreatetruecolor( $new_width, $new_height );
imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
imagedestroy( $src );
imagepng( $dst, $target_filename ); // adjust format as needed
imagedestroy( $dst );
}
}
}
If you want to use Imagick out of the box (included with most PHP distributions), it's as easy as...
$image = new Imagick();
$image_filehandle = fopen('some/file.jpg', 'a+');
$image->readImageFile($image_filehandle);
$image->scaleImage(100,200,FALSE);
$image_icon_filehandle = fopen('some/file-icon.jpg', 'a+');
$image->writeImageFile($image_icon_filehandle);
You will probably want to calculate width and height more dynamically based on the original image. You can get an image's current width and height, using the above example, with $image->getImageHeight(); and $image->getImageWidth();
This thing worked for me.
No any external liabraries used
define ("MAX_SIZE","3000");
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image =$_FILES["image-1"]["name"];
$uploadedfile = $_FILES['image-1']['tmp_name'];
if ($image)
{
$filename = stripslashes($_FILES['image-1']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo "Unknown Extension..!";
}
else
{
$size=filesize($_FILES['image-1']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
echo "File Size Excedeed..!!";
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['image-1']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['image-1']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
echo $scr;
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=1000;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=1000;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
$filename = "../images/product-image/Cars/". $_FILES['image-1']['name'];
$filename1 = "../images/product-image/Cars/small". $_FILES['image-1']['name'];
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}
}
You can use Imagine library also. It uses GD and Imagick.
index.php :
<!DOCTYPE html>
<html>
<head>
<title>PHP Image resize to upload</title>
</head>
<body>
<div class="container">
<form action="pro.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Submit" />
</form>
</div>
</body>
</html>
upload.php
<?php
if(isset($_POST["submit"])) {
if(is_array($_FILES)) {
$file = $_FILES['image']['tmp_name'];
$sourceProperties = getimagesize($file);
$fileNewName = time();
$folderPath = "upload/";
$ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$imageType = $sourceProperties[2];
switch ($imageType) {
case IMAGETYPE_PNG:
$imageResourceId = imagecreatefrompng($file);
$targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
imagepng($targetLayer,$folderPath. $fileNewName. "_thump.". $ext);
break;
case IMAGETYPE_GIF:
$imageResourceId = imagecreatefromgif($file);
$targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
imagegif($targetLayer,$folderPath. $fileNewName. "_thump.". $ext);
break;
case IMAGETYPE_JPEG:
$imageResourceId = imagecreatefromjpeg($file);
$targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
imagejpeg($targetLayer,$folderPath. $fileNewName. "_thump.". $ext);
break;
default:
echo "Invalid Image type.";
exit;
break;
}
move_uploaded_file($file, $folderPath. $fileNewName. ".". $ext);
echo "Image Resize Successfully.";
}
}
function imageResize($imageResourceId,$width,$height) {
$targetWidth =200;
$targetHeight =200;
$targetLayer=imagecreatetruecolor($targetWidth,$targetHeight);
imagecopyresampled($targetLayer,$imageResourceId,0,0,0,0,$targetWidth,$targetHeight, $width,$height);
return $targetLayer;
}
?>
I followed the steps at https://www.w3schools.com/php/php_file_upload.asp and http://www.w3bees.com/2013/03/resize-image-while-upload-using-php.html to produce this solution:
In my view (I am using the MVC paradigm, but it could be your .html or .php file, or the technology that you use for your front-end):
<form action="../../photos/upload.php" method="post" enctype="multipart/form-data">
<label for="quantity">Width:</label>
<input type="number" id="picture_width" name="picture_width" min="10" max="800" step="1" value="500">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
My upload.php:
<?php
/* Get original image x y*/
list($w, $h) = getimagesize($_FILES['fileToUpload']['tmp_name']);
$new_height=$h*$_POST['picture_width']/$w;
/* calculate new image size with ratio */
$ratio = max($_POST['picture_width']/$w, $new_height/$h);
$h = ceil($new_height / $ratio);
$x = ($w - $_POST['picture_width'] / $ratio) / 2;
$w = ceil($_POST['picture_width'] / $ratio);
/* new file name */
//$path = 'uploads/'.$_POST['picture_width'].'x'.$new_height.'_'.basename($_FILES['fileToUpload']['name']);
$path = 'uploads/'.basename($_FILES['fileToUpload']['name']);
/* read binary data from image file */
$imgString = file_get_contents($_FILES['fileToUpload']['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($_POST['picture_width'], $new_height);
imagecopyresampled($tmp, $image,
0, 0,
$x, 0,
$_POST['picture_width'], $new_height,
$w, $h);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($path,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
//echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
//echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($path)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
/* Save image */
switch ($_FILES['fileToUpload']['type']) {
case 'image/jpeg':
imagejpeg($tmp, $path, 100);
break;
case 'image/png':
imagepng($tmp, $path, 0);
break;
case 'image/gif':
imagegif($tmp, $path);
break;
default:
exit;
break;
}
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
/* cleanup memory */
imagedestroy($image);
imagedestroy($tmp);
}
?>
The name of the folder where pictures are stored is called 'uploads/'. You need to have that folder previously created and that is where you will see your pictures. It works great for me.
NOTE: This is my form:
The code is uploading and resizing pictures properly. I used this link as a guide: http://www.w3bees.com/2013/03/resize-image-while-upload-using-php.html. I modified it because in that code they specify both width and height of resized pictures. In my case, I only wanted to specify width. The height I automatically calculated it proportionally, just keeping proper picture proportions. Everything works perfectly. I hope this helps.
A full example with Zebra_Image library, that I think is so easy and useful. There are a lot of code, but if you read it, there are a lot of comments too so you can make copy and paste to use it quickly.
This example validates image format, size and replace image size with custom resolution. There is Zebra library and documentation (download only Zebra_Image.php file).
Explanation:
An image is uploaded to server by uploadFile function.
If image has been uploaded correctly, we recover this image and its path by getUserFile function.
Resize image to custom width and height and replace at same path.
Main function
private function uploadImage() {
$target_file = "../img/blog/";
//this function could be in the same PHP file or class. I use a Helper (see bellow)
if(UsersUtils::uploadFile($target_file, $this->selectedBlog->getId())) {
//This function is at same Helper class.
//The image will be returned allways if there isn't errors uploading it, for this reason there aren't validations here.
$blogPhotoPath = UsersUtils::getUserFile($target_file, $this->selectedBlog->getId());
// create a new instance of the class
$imageHelper = new Zebra_Image();
// indicate a source image
$imageHelper->source_path = $blogPhotoPath;
// indicate a target image
$imageHelper->target_path = $blogPhotoPath;
// since in this example we're going to have a jpeg file, let's set the output
// image's quality
$imageHelper->jpeg_quality = 100;
// some additional properties that can be set
// read about them in the documentation
$imageHelper->preserve_aspect_ratio = true;
$imageHelper->enlarge_smaller_images = true;
$imageHelper->preserve_time = true;
$imageHelper->handle_exif_orientation_tag = true;
// resize
// and if there is an error, show the error message
if (!$imageHelper->resize(450, 310, ZEBRA_IMAGE_CROP_CENTER)) {
// if there was an error, let's see what the error is about
switch ($imageHelper->error) {
case 1:
echo 'Source file could not be found!';
break;
case 2:
echo 'Source file is not readable!';
break;
case 3:
echo 'Could not write target file!';
break;
case 4:
echo 'Unsupported source file format!';
break;
case 5:
echo 'Unsupported target file format!';
break;
case 6:
echo 'GD library version does not support target file format!';
break;
case 7:
echo 'GD library is not installed!';
break;
case 8:
echo '"chmod" command is disabled via configuration!';
break;
case 9:
echo '"exif_read_data" function is not available';
break;
}
} else {
echo 'Image uploaded with new size without erros');
}
}
}
External functions or use at same PHP file removing public static qualifiers.
public static function uploadFile($targetDir, $fileName) {
// File upload path
$fileUploaded = $_FILES["input-file"];
$fileType = pathinfo(basename($fileUploaded["name"]),PATHINFO_EXTENSION);
$targetFilePath = $targetDir . $fileName .'.'.$fileType;
if(empty($fileName)){
echo 'Error: any file found inside this path';
return false;
}
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf');
if(in_array($fileType, $allowTypes)){
//Max buffer length 8M
var_dump(ob_get_length());
if(ob_get_length() > 8388608) {
echo 'Error: Max size available 8MB';
return false;
}
// Upload file to server
if(move_uploaded_file($fileUploaded["tmp_name"], $targetFilePath)){
return true;
}else{
echo 'Error: error_uploading_image.';
}
}else{
echo 'Error: Only files JPG, JPEG, PNG, GIF y PDF types are allowed';
}
return false;
}
public static function getUserFile($targetDir, $userId) {
$userImages = glob($targetDir.$userId.'.*');
return !empty($userImages) ? $userImages[0] : null;
}
This class you can use with any framework or core PHP.
For complete detail visit the below link.
https://learncodeweb.com/web-development/laravel-9-upload-multiple-files-and-image-resizer/
There are many libs that you can use to upload & resize multiple images in the Laravel. I come up with a simple and easy solution, it is a GD base class.
All you need to install via composer with the help of the below command.
composer require learncodeweb/filesupload
After installation recreates the autoload file with the help of the below command. (optional)
composer dump-autoload
How to import and use in the Larvel 8/9 (Tested).
use anyFileUpload\FilesUploadAndImageResize as anyFilesUpload;
$files = new anyFilesUpload('array', ['jpg', 'jpeg', 'png'], public_path('uploads'), 0777);
$files->uploadFiles('files', 250, '', '', 100, '850', ['350']);
dd($files->uploadedData);
After uploading files to the server, it returns all uploaded file names. You can dump those in your DB.
Provided Functionalities
Upload Single Or Multiple Files.
Upload Any Type Of Files (Not Only Images).
The image file can Resize.
Create Image Thumbnails (With Keep The Image Aspect Ratio).
You can add a watermark (Text, Image).
Easy Integration With Forms.
Create Any Number Of Thumbnails Under One Upload.
Customizable Paths To Thumbnails Folders.
Customizable Thumbnails Sizes And Dimensions.
Files Extension Filters.
File Size Limit for Uploading.
Based on zeusstl soulution you can add this to 4th line if you want that either of width or height use maxDim and highest measure is set based on this:
if ($height > $width) {
$maxDim = $maxDim * ($height/$width);
} else {
$maxDim = $maxDim * ($width/$height);
}
Download library file Zebra_Image.php belo link
https://drive.google.com/file/d/0Bx-7K3oajNTRV1I2UzYySGZFd3M/view
resizeimage.php
<?php
require 'Zebra_Image.php';
// create a new instance of the class
$resize_image = new Zebra_Image();
// indicate a source image
$resize_image->source_path = $target_file1;
$ext = $photo;
// indicate a target image
$resize_image->target_path = 'images/thumbnil/' . $ext;
// resize
// and if there is an error, show the error message
if (!$resize_image->resize(200, 200, ZEBRA_IMAGE_NOT_BOXED, -1));
// from this moment on, work on the resized image
$resize_image->source_path = 'images/thumbnil/' . $ext;
?>
I've got an upload function that allows both Jpegs and PNG's. After the image is uploaded, a php file is called that handles a crop function to crop the uploaded image.
After the image is cropped, it is once again saved to the server under a new name. In this current setup, only jpegs are able to be written to the server. Anything else will draw a black image.
I was wondering How I write this code so that the crop also allows PNG's
The code that handles the crop:
$imageLocation = $_SESSION['image_location'];
$newNameOverwrite = $_SESSION['new_name'];
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$jpeg_quality = 100;
$src = $imageLocation;
list($width, $height, $type, $attr) = getimagesize($src);
$targ_w = $width;
$targ_h = $height;
$img_r = imagecreatefromjpeg($src);
$dst_r = imagecreatetruecolor($_POST[('w')], $_POST[('h')]);
$uploadLocation = 'uploads/';
$name = $uploadLocation.'resized_'.$newNameOverwrite;
imagecopy(
$dst_r, $img_r,
0, 0, $_POST['x'], $_POST['y'],
$_POST['w'], $_POST['h']
);
imagejpeg($dst_r,$name,100);
$imageCropped = $name;
$_SESSION['image_cropped'] = $imageCropped;
//Thumbnail generate
include('SimpleImage.php');
$imageThumbnail = new SimpleImage();
$imageThumbnail->load($name);
$imageThumbnail->resizeToWidth(200);
$imageThumbnail->save($uploadLocation.'resizedThumbnail_'.$newNameOverwrite);
$imageThumbnailCropped = ($uploadLocation.'resizedThumbnail_'.$newNameOverwrite);
$imageThumbnailCroppedSession = $imageThumbnailCropped;
$_SESSION['image_cropped_thumbnail'] = $imageThumbnailCroppedSession;
}
Updated code:
$imageType = $_SESSION['image_type'];
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$jpeg_quality = 100;
$src = $imageLocation;
list($width, $height, $type, $attr) = getimagesize($src);
$targ_w = $width;
$targ_h = $height;
if ($imageType == '.jpg' || $imageType == '.jpeg'){
$img_r = imagecreatefromjpeg($src);
}
if ($imageType == '.png'){
$img_r = imagecreatefrompng($src);
}
$dst_r = imagecreatetruecolor($_POST[('w')], $_POST[('h')]);
$uploadLocation = 'uploads/';
$name = $uploadLocation.'resized_'.$newNameOverwrite;
imagecopy(
$dst_r, $img_r,
0, 0, $_POST['x'], $_POST['y'],
$_POST['w'], $_POST['h']
);
var_dump($imageType);
if ($imageType == '.png'){
imagepng($dst_r,$name);
}
if ($imageType == '.jpg' || $imageType == '.jpeg'){
imagejpeg($dst_r,$name, 100);
}
$imageCropped = $name;
$_SESSION['image_cropped'] = $imageCropped;
include('SimpleImage.php');
$imageThumbnail = new SimpleImage();
$imageThumbnail->load($name);
$imageThumbnail->resizeToWidth(200);
$imageThumbnail->save($uploadLocation.'resizedThumbnail_'.$newNameOverwrite);
$imageThumbnailCropped = ($uploadLocation.'resizedThumbnail_'.$newNameOverwrite);
$imageThumbnailCroppedSession = $imageThumbnailCropped;
$_SESSION['image_cropped_thumbnail'] = $imageThumbnailCroppedSession;
}
Use PHP to determine what type of image it is, then dynamically use *_png functions instead of *_jpeg ones. IE, instead of imagecreatefromjpeg use imagecreatefrompng
Can you help me with my code in php?
I don't know how make my pictures transparent. They have black background after the uploading. I have the code here. (and some text for small post and content)
Thhank you.
<?php
function zmensi_obrazok($image_max_width, $image_max_height, $obrazok, $obrazok_tmp, $obrazok_size, $filename){
$postvars = array(
"image" => $obrazok,
"image_tmp" => $obrazok_tmp,
"image_size" => $obrazok_size,
"image_max_width" => $image_max_width,
"image_max_height" => $image_max_height
);
$valid_exts = array("jpg","jpeg","png");
$ext = end(explode(".",strtolower($obrazok)));
if($postvars["image_size"] <= 1024000){
if(in_array($ext,$valid_exts)){
if($ext == "jpg" || $ext == "jpeg"){
$image = imagecreatefromjpeg($postvars["image_tmp"]);
}
else if($ext == "png"){
$image = imagecreatefrompng($postvars["image_tmp"]);
}
list($width,$height) = getimagesize($postvars["image_tmp"]);
$old_width = imagesx($image);
$old_height = imagesy($image);
$scale = min($postvars["image_max_width"]/$old_width, $postvars["image_max_height"]/$old_height);
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
$tmp = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($tmp,$image,0,0,0,0,$new_width,$new_height,$width,$height);
imagejpeg($tmp,$filename,100);
return "";
imagedestroy($image);
imagedestroy($tmp);
}
}
}
?>
I think this link will answer your question:
http://www.php.net/manual/pl/function.imagecopyresampled.php#104028
In your code the answer will be something like:
// preserve transparency
if($ext == "gif" or $ext == "png"){
imagecolortransparent($tmp, imagecolorallocatealpha($tmp, 0, 0, 0, 127));
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
}
Paste this before executing imagecopyresampled.
If you did want to save to a JPEG rather than saving to a PNG, you can just change the background colour of the target image to white before you do the copy:
$tmp = imagecreatetruecolor($new_width,$new_height);
imagefilledrectangle($tmp, 0, 0, $new_width, $new_height, imagecolorallocate($tmp, 255, 255, 255));
imagecopyresampled($tmp,$image,0,0,0,0,$new_width,$new_height,$width,$height);
Then you'll end up with a JPEG without any transparency, but the background colour will be white rather than black.
I am uploading product screenshots to my website... I want to upload the original image as it is and also create a thumbnail for it, but after uploading both the files the filesize of the thumbnail created is a bit larger than expected. Is there any way I could reduce the filesize of the thumbnail without compromising much on the quality in php or by using Imagemagick( which I have no idea how to use but I'm willing to learn if needed)...
Below is the code I'm using to upload my files..
<form action="<?php echo $_server['php-self']; ?>" method="post" enctype="multipart/form-data" id="something" class="uniForm">
<input name="new_image" id="new_image" size="30" type="file" class="fileUpload" />
<button name="submit" type="submit" class="submitButton">Upload/Resize Image</button>
<?php
if(isset($_POST['submit'])){
if (isset ($_FILES['new_image'])){
$imagename = $_FILES['new_image']['name'];
$source = $_FILES['new_image']['tmp_name'];
$target = "images/".$imagename;
move_uploaded_file($source, $target);
$imagepath = $imagename;
$save = "images/" . $imagepath; //This is the new file you saving
$file = "images/" . $imagepath; //This is the original file
list($width, $height) = getimagesize($file) ;
$tn = imagecreatetruecolor($width, $height) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $width, $height, $width, $height) ;
imagejpeg($tn, $save, 100) ;
$save = "images/sml_" . $imagepath; //This is the new file you saving
$file = "images/" . $imagepath; //This is the original file
list($width, $height) = getimagesize($file) ;
$modwidth = 130;
$diff = $width / $modwidth;
$modheight = 185;
$tn = imagecreatetruecolor($modwidth, $modheight) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
imagejpeg($tn, $save, 100) ;
echo "Large image: <img src='images/".$imagepath."'><br>";
echo "Thumbnail: <img src='images/sml_".$imagepath."'>";
}
} ?>
Kindly point me in the right direction...Thanks
Don't pass 100 as the quality for imagejpeg() - anything over 90 is generally overkill and just gets you a bigger JPEG. For a thumbnail, try 75 and work downwards until the quality/size tradeoff is acceptable.
//try this
imagejpeg($tn, $save, 75) ;
Hello #halocursed I just try to compress using your code for different image type like png and gif than image comes black. So, I modify the block of code and good working for jpg, png.
<?php
if(isset($_POST['submit'])){
if (isset ($_FILES['new_image'])){
// print_r($_FILES); die;
$imagename = $_FILES['new_image']['name'];
$source = $_FILES['new_image']['tmp_name'];
$target = "images/".$imagename;
move_uploaded_file($source, $target);
$imagepath = $imagename;
$save = "images/" . $imagepath; //This is the new file you saving
$file = "images/" . $imagepath; //This is the original file
list($width, $height) = getimagesize($file);
$tn = imagecreatetruecolor($width, $height);
//$image = imagecreatefromjpeg($file);
$info = getimagesize($target);
if ($info['mime'] == 'image/jpeg'){
$image = imagecreatefromjpeg($file);
}elseif ($info['mime'] == 'image/gif'){
$image = imagecreatefromgif($file);
}elseif ($info['mime'] == 'image/png'){
$image = imagecreatefrompng($file);
}
imagecopyresampled($tn, $image, 0, 0, 0, 0, $width, $height, $width, $height);
imagejpeg($tn, $save, 60);
echo "Large image: ".$imagepath;
}
}
?>
75 is the default quality setting, however you'll notice quality decrease considerably if you use it. 90 gives you a great image quality and reduces the file size in half, if you want to decrease the file size even more use 85 or 80 but nothing bellow that.
It should be 60, it stands for 60 percent.
Example:
If you open an image in Photoshop and try save it for web and select jpg, you can see that by using 60 it's still under high quality, but lower file size. If you would like lower, with more degradation, meaning the colors are distorted more.
More than 60 does not give you anything better, only larger file size.
It's standard image optimization for web. Keep high quality but keep file size as low as possible.
A quality setting of 100% ist quite to large. try 85 or 90% you wont see a difference on most of the images.
see:
http://www.ampsoft.net/webdesign-l/jpeg-compression.html
If using jpeg, using a quality between 75 and 85 is generally more than acceptable (and 100 takes way too much space, for a gain that is not that important, btw), at least for photos.
As a sidenote, if you are dealing with screenshots, using PNG might get you a better quality : jpeg degrades the images (it is quite OK for photos, but for screenshots, with fonts that are drawn by pixels, it can bring some not nice-looking effect)
it moving compressed image with original. actually i want to move only compressed image that starts with "rxn-".
include("do.php");
session_start();
if(is_array($_FILES)) {
for($i=0; $i<count($_FILES['userImage']['tmp_name']); $i++){
if(is_uploaded_file($_FILES['userImage']['tmp_name'][$i])) {
$sourcePath = $_FILES['userImage']['tmp_name'][$i];
$upload_dir = "images/";
$targetPath = "images/".basename($_FILES['userImage']['name'][$i]);
$source_image = "images/".basename($_FILES['userImage']['name'][$i]);
$imageName =$_FILES['userImage']['name'][$i];
$imageFileType = strtolower(pathinfo($targetPath,PATHINFO_EXTENSION));
$check = getimagesize($_FILES["userImage"]["tmp_name"][$i]);
if (file_exists($targetPath)) {
// echo "<span style='color:red;'> file already exists</span> ";
}
if($check !== false) {
// echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "<span style='color:red;'>File is not an image.</span><br>";
$uploadOk = 0;
}
if($imageFileType == "jpg" || $imageFileType == "png" || $imageFileType == "jpeg"
|| $imageFileType =="gif" ) {
if(move_uploaded_file($sourcePath,$targetPath))
//if(1)
{
$image_destination = $upload_dir."rxn-".$imageName;
$compress_images = compressImage($source_image, $image_destination);
$pId=$_SESSION['pId'];
$sql="insert into image(p_id,img_path) values('$pId','$compress_images')";
$result = mysql_query($sql);
echo "
<div class='col-sm-3' id='randomdiv' style='padding-bottom: 15px;'>
<div class='bg_prcs uk-height-small uk-flex uk-flex-center uk-flex-middle uk-background-cover uk-light uk-card-default uk-card-hover imgt' data-src='$image_destination' uk-img>
</div>
</div>
";
}
}
else{ echo "<span style='color:red;'> only JPG, JPEG, PNG & GIF files are allowed.</span>";
}
}
}
}
// created compressed JPEG file from source file
function compressImage($source_image, $compress_image) {
$image_info = getimagesize($source_image);
if ($image_info['mime'] == 'image/jpeg') {
$source_image = imagecreatefromjpeg($source_image);
imagejpeg($source_image, $compress_image, 75);
} elseif ($image_info['mime'] == 'image/gif') {
$source_image = imagecreatefromgif($source_image);
imagegif($source_image, $compress_image, 75);
} elseif ($image_info['mime'] == 'image/png') {
$source_image = imagecreatefrompng($source_image);
imagepng($source_image, $compress_image, 6);
}
return $compress_image;
}
?>