I want to upload multiple images for each item.Images are uploading successfully but it takes a lot time to load those images.So,i want to save the uploaded image as jpeg so that it can be loaded easily.
Use Php library for images GD2 or use SimpleImage PHP class
$src='uploads/'.$_REQUEST['name'];
$newsrc='profiles/'.$_REQUEST['name'];
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$targ_w=$_POST['w'];
$targ_h=$_POST['h'];
$jpeg_quality = 90;
$img_r = imagecreatefromjpeg($src);//you can chose other option like imagecreatetruecolor($_POST['w'],$_POST['h']) etc
$dst_r = ImageCreateTrueColor( $_POST['w'],$_POST['h']);
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],$targ_w,$targ_h,$_POST['w'],$_POST['h']);
imagejpeg($dst_r,$newsrc,$jpeg_quality) or die("Unable to save image");
imagedestroy($img_r);
}
you can use below code for upload image that will compress your image and you can also convert it in to jpg with normal modification.
<?php
/*
Template Name: image compress
*/
if(isset($_POST['submit'])){
//print each file name
//echo count($_FILES['new_image']['name']);
for($i=0; $i<count($_FILES['new_image']['name']); $i++)
{
$imagename = $_FILES['new_image']['name'][$i];
$source = $_FILES['new_image']['tmp_name'][$i];
$a=$_SERVER['DOCUMENT_ROOT'];
$target = "full/path/where/you/save /image/".$imagename;
move_uploaded_file($source, $target);
$imagepath = $imagename;
//$imagename = explode('.',$imagepath);
$save = "full/path/where/you/save /image/". $imagepath; //This is the new file you saving
$file = "full/path/where/you/save /image/". $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) ;
//.image_type_to_extension(IMAGETYPE_JPEG) image file convert
imagejpeg($tn, $save,50) ;
$thumb = imagecreatetruecolor($newwidth, $newheight);
/*$save = $a."/demo/mainn/". $imagepath; //This is the new file you saving
$file = "full/path/where/you/save /image/". $imagepath; //This is the original file
list($width, $height) = getimagesize($file) ;
$modwidth = 176;
$diff = $width / $modwidth;
$modheight = 255;
$tn = imagecreatetruecolor($modwidth, $modheight) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
imagejpeg($tn, $save, 80); */
}
}
?>
<form action="<?php ?>" method="post" enctype="multipart/form-data" id="something" class="uniForm">
<!--<input name="new_image" id="new_image" size="30" type="file" class="fileUpload" />-->
<input name="new_image[]" type="file" multiple="multiple" />
<button name="submit" type="submit" class="submitButton">Upload/Resize Image</button>
</form>
put this on you server than upload image it will compress 20% when it loads that take not much time.
Related
Can someone show me how to not have watermark with this function? all i want it to do is just resize image without any watermark.
Issue i am facing with the codes right now is say 2 out 100 images being uploaded by users the image seems to be completely black
$image_path = "../css/images/logo.png";
function watermark_image_post($oldimage_name, $new_image_name){
global $image_path;
list($owidth,$oheight) = getimagesize($oldimage_name);
$width = 720; $height = 450;
$im = imagecreatetruecolor($width, $height);
$img_src = imagecreatefromjpeg($oldimage_name);
imagecopyresampled($im, $img_src, 0, 0, 0, 0, $width, $height, $owidth, $oheight);
$watermark = imagecreatefrompng($image_path);
list($w_width, $w_height) = getimagesize($image_path);
$pos_x = $width - $w_width;
$pos_y = $height - $w_height;
imagecopy($im, $watermark, $pos_x, $pos_y, 0, 0, $w_width, $w_height);
imagejpeg($im, $new_image_name, 90);
imagedestroy($im);
unlink($oldimage_name);
return true;
}
the html
<div class="row form-group">
<img id="output" class="imgoutput wdt"/>
<div class="col-md-12">
<label for="activities">Please attach your photo (250x250)</label>
<input type="file" name="file" id="file" accept=".jpg, .jpeg" onChange="loadFile(event)" class="form-control" />
</div>
</div>
This is how i error handle
if($_FILES['file']['size'] == '0'){
$error[] = 'Please attach your photo.';
}elseif($_FILES["file"]["size"] > 2097152){
$error[] = 'Selected image size is too large, upload under 2mb.';
}elseif(!in_array($_FILES["file"]["type"], array("image/jpg", "image/jpeg"))){
$error[] = 'We accept only (JPG / JPEG) image file type.';
}
here is the part used in form, anyway to resize directly with the below code?
if($_FILES['file']['name']!='')
{
$tmp_name = $_FILES["file"]["tmp_name"];
$namefile = $_FILES["file"]["name"];
$cname = str_replace(' ', '-', $candidate_name);
$ext = end(explode(".", $namefile));
$fileUpload = move_uploaded_file($tmp_name,"uploads/images/".$image_name);
$image_name= $cname.'-'.time().".".$ext;
watermark_image_post($tmp_name,"uploads/images/".$image_name);
$img = ''.$image_name.'';
}
Thanks alot
I'm trying to save a thumbnail image onto my server using the below code...
// Get Variables
$image = $_FILES['file']['tmp_name'];
$image_name = $_FILES['file']['name'];
$page = $_POST['page'];
$sub_category = $_POST['sub_category'];
$title = $_POST['title'];
$description = $_POST['description'];
$paypal = $_POST['paypal'];
// Resize Image
$image_size = getimagesize($image);
$image_width = $image_size[0];
$image_height = $image_size[1];
// Resizes image to roughly 150px by 100px
$new_size = ($image_width + $image_height)/($image_width * ($image_height / 65));
$new_width = $image_width * $new_size;
$new_height = $image_height * $new_size;
// Image locations on server
$location_large = "Product Images/Large Images/{$image_name}";
$location_small = "Product Images/Small Images/{$image_name}";
// Create New Image
$new_image = imagecreatetruecolor($new_width, $new_height);
$source_image = imagecreatefromjpeg($image);
imagecopyresampled($new_image, $source_image, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height);
imagejpeg($new_image, $location_small, 100);
// Upload original image
move_uploaded_file($image, "../Product Images/Large Images/{$image_name}");
All server permissions are fine! 0777!
Saves original image into 'Large Images' no problems.
Since you upload the large image to the parent folder you could do:
if (!imagejpeg($new_image, '../' . $location_small, 100))
{
// Here you make sure this is the function that failed
die('Imagejpeg failed');
}
In one of my applications, I'm using the code snippet below to copy uploaded images to a directory. It works fine but copying large images (> 2MB) takes more time than ideal and I really don't need images this big, so, I'm looking for a way to resize the images. How to achieve this using PHP?
<?php
$uploadDirectory = 'images/0001/';
$randomNumber = rand(0, 99999);
$filename = basename($_FILES['userfile']['name']);
$filePath = $uploadDirectory.md5($randomNumber.$filename);
// Check if the file was sent through HTTP POST.
if (is_uploaded_file($_FILES['userfile']['tmp_name']) == true) {
// Validate the file size, accept files under 5 MB (~5e+6 bytes).
if ($_FILES['userfile']['size'] <= 5000000) {
// Move the file to the path specified.
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $filePath) == true) {
// ...
}
}
}
?>
Finally, I've discovered a way that fit my needs. The following snippet will resize an image to the specified width, automatically calculating the height in order to keep the proportion.
$image = $_FILES["image"]["tmp_name"];
$resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";
copy($_FILES, $resizedDestination);
$imageSize = getImageSize($image);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$DESIRED_WIDTH = 100;
$proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);
$originalImage = imageCreateFromJPEG($image);
$resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);
imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
imageJPEG($resizedImage, $resizedDestination);
imageDestroy($originalImage);
imageDestroy($resizedImage);
To anyone else seeking a complete example, create two files:
<!-- send.html -->
<html>
<head>
<title>Simple File Upload</title>
</head>
<body>
<center>
<div style="margin-top:50px; padding:20px; border:1px solid #CECECE;">
Select an image.
<br/>
<br/>
<form action="receive.php" enctype="multipart/form-data" method="post">
<input type="file" name="image" size="40">
<input type="submit" value="Send">
</form>
</div>
</center>
</body>
<?php
// receive.php
$randomNumber = rand(0, 99999);
$uploadDirectory = "images/";
$filename = basename($_FILES['file_contents']['name']);
$destination = $uploadDirectory.md5($randomNumber.$filename).".jpg";
echo "File path:".$filePath."<br/>";
if (is_uploaded_file($_FILES["image"]["tmp_name"]) == true) {
echo "File successfully received through HTTP POST.<br/>";
// Validate the file size, accept files under 5 MB (~5e+6 bytes).
if ($_FILES['image']['size'] <= 5000000) {
echo "File size: ".$_FILES["image"]["size"]." bytes.<br/>";
// Resize and save the image.
$image = $_FILES["image"]["tmp_name"];
$resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";
copy($_FILES, $resizedDestination);
$imageSize = getImageSize($image);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$DESIRED_WIDTH = 100;
$proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);
$originalImage = imageCreateFromJPEG($image);
$resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);
imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
imageJPEG($resizedImage, $resizedDestination);
imageDestroy($originalImage);
imageDestroy($resizedImage);
// Save the original image.
if (move_uploaded_file($_FILES['image']['tmp_name'], $destination) == true) {
echo "Copied the original file to the specified destination.<br/>";
}
}
}
?>
I made a small function to resize images, the function is below:
function resize_image($path, $width, $height, $update = false) {
$size = getimagesize($path);// [width, height, type index]
$types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
if ( array_key_exists($size['2'], $types) ) {
$load = 'imagecreatefrom' . $types[$size['2']];
$save = 'image' . $types[$size['2']];
$image = $load($path);
$resized = imagecreatetruecolor($width, $height);
$transparent = imagecolorallocatealpha($resized, 0, 0, 0, 127);
imagesavealpha($resized, true);
imagefill($resized, 0, 0, $transparent);
imagecopyresampled($resized, $image, 0, 0, 0, 0, $width, $height, $size['0'], $size['1']);
imagedestroy($image);
return $save($resized, $update ? $path : null);
}
}
And here's how you use it:
if ( resize_image('dir/image.png', 50, 50, true) ) {// resize image.png to 50x50
echo 'image resized!';
}
there is 1 very simple image re-size function for all image types that keeps transparency and is very easy to use
check out :
https://github.com/Nimrod007/PHP_image_resize
hope this helps
ImageMagick is the fastest and probably the best way to resize images in PHP. Check out different examples here. This sample shows how to resize and image on upload.
Thanks to Mateus Nunes!
i edited his work a bit to get transparent pngs working:
$source = $_FILES["..."]["tmp_name"];
$destination = 'abc/def/ghi.png';
$maxsize = 45;
$size = getimagesize($source);
$width_orig = $size[0];
$height_orig = $size[1];
unset($size);
$height = $maxsize+1;
$width = $maxsize;
while($height > $maxsize){
$height = round($width*$height_orig/$width_orig);
$width = ($height > $maxsize)?--$width:$width;
}
unset($width_orig,$height_orig,$maxsize);
$images_orig = imagecreatefromstring( file_get_contents($source) );
$photoX = imagesx($images_orig);
$photoY = imagesy($images_orig);
$images_fin = imagecreatetruecolor($width,$height);
imagesavealpha($images_fin,true);
$trans_colour = imagecolorallocatealpha($images_fin,0,0,0,127);
imagefill($images_fin,0,0,$trans_colour);
unset($trans_colour);
ImageCopyResampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY);
unset($photoX,$photoY,$width,$height);
imagepng($images_fin,$destination);
unset($destination);
ImageDestroy($images_orig);
ImageDestroy($images_fin);
You could also use an x*y/width method for resizing and then calling imagecopyresampled() like is shown at http://www.virtualsecrets.com/upload-resize-image-php-mysql.html That page also puts images (after resizing) into mySQL via the PDO.
The code below will resize an image to 50*50 but whenever i select the name of the image in my database and put it like these $filename = 'folder/$imagename'; it does not work how can i fix these.
<?php
$filename = 'folder/Aizen.jpg';
$width = 50;
$height = 50;
header('Content-type: image/jpeg');
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagejpeg($image_p, null, 100);
?>
<img src="<?= $filename ?>" alt="" />
<?php
/*
Database Query
*/
$myImageFromTableData = $row['Image'];
/*
Start my Code
*/
$filename = $myImageFromTableData;
Just one small issue. You have not shown your database code.
You can't use variables in single quote strings. Try it like this.
$filename = 'folder/'.$imagename;
i have this image upload script.
<?php
if(isset($_POST['submit'])){
if (isset ($_FILES['new_image'])){
$imagename = $_FILES['new_image']['name'];
$source = $_FILES['new_image']['tmp_name'];
$target = "temporary_images/".$imagename;
move_uploaded_file($source, $target);
$imagepath = $imagename;
$save = "temporary_images/" . $imagepath; //This is the new file you saving
$file = "temporary_images/" . $imagepath; //This is the original file
list($width, $height) = getimagesize($file) ;
$modwidth = 350;
$modheight = 100;
$tn = imagecreatetruecolor($modwidth, $modheight) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
imagejpeg($tn, $save, 100) ;
$save = "temporary_images/sml_" . $imagepath; //This is the new file you saving
$file = "temporary_images/" . $imagepath; //This is the original file
list($width, $height) = getimagesize($file) ;
$modwidth = 80;
$modheight = 100;
$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='temporary_images/".$imagepath."'><br>";
}
}
I need the script to write the name of the file in the form
<form>
<input name="animeinput" id="animeinput" size="20" class="textbox">
</form>
So basically i need my upload script to write $imagepath (the filename that is used for storing the image) into the form when an image has been uploaded.
How do i do this?
If you're wanting to add to your script, which you previously mentioned is displaying the image, then is this what you mean?
...
echo "Large image: <img src='temporary_images/".$imagepath."'><br>";
echo "<form>";
echo '<input type="text" value="' . $imagePath . '" name="animeinput" id="animeinput" size="20" class="textbox">';
echo "</form>";
...
I'm not completely sure what you mean, but this should work:
<form>
<input value="<?php echo htmlspecialchars($imagepath); ?>" name="animeinput" id="animeinput" size="20" class="textbox">
</form>