My Idea is to upload a image file that is combined with a watermark. This code needs to work like this. On a portfolio website, the owner uploads an image he wants to sell throught the CMS i made. But because he wants to sell the image he wants it to come on the site with a watermark.
So my idea, i let him upload the original image, then i get the image through the $_Files() en combine it with a watermark, make it one image again and upload that image.
Now is my question, how do i upload a image created in PHP i tried to convert it to Base64 but with no luck. Here is my code.
Sorry for the bad english!
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$filetype = substr($target_file, -4);
if($filetype == ".gif") $image = #imagecreatefromgif($_FILES["fileToUpload"]["tmp_name"]);
if($filetype == ".jpg") $image = #imagecreatefromjpeg($_FILES["fileToUpload"]["tmp_name"]);
if($filetype == ".png") $image = #imagecreatefrompng($_FILES["fileToUpload"]["tmp_name"]);
if (empty($image)) die();
$watermark = #imagecreatefrompng('watermark.png');
$imagewidth = imagesx($image);
$imageheight = imagesy($image);
$watermarkwidth = imagesx($watermark);
$watermarkheight = imagesy($watermark);
$startwidth = (($imagewidth - $watermarkwidth)/2);
$startheight = (($imageheight - $watermarkheight)/2);
imagecopy($image, $watermark, $startwidth, $startheight, 0, 0, $watermarkwidth, $watermarkheight);
file_put_contents($target_file, $image)
Try this:
imagejpeg($image, $target_file);
or imagepng($image, $target_file);
or imagegif($image, $target_file);
Related
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');
}
I'm kind of a beginner in PHP and here's what I'm trying to do:
Recieve an uploaded image and move it to temp/ folder
Examine it and decide whether it needs to be resized or not (it needs, if it's not 135px wide)
If needs to be resized, resize it and save as results/{number}_cover.jpg
If it doesn't, copy an uploaded image right away to the same place, without resizing
And here's my code:
$target_path = "temp/";
$target_path = $target_path . basename($_FILES["file" . $a]["name"]);
move_uploaded_file($_FILES["file" . $a]["tmp_name"], $target_path);
list($current_width, $current_height, $type, $attr) = getimagesize($target_path);
if($current_width != 135) {
$filename = $a . "_cover.jpg";
$result_image = "results/" . $filename;
$writing = fopen($result_image, 'w');
$scale = (135 / $current_width);
$new_width = 135;
$new_height = $current_height * $scale;
$result_image = imagecreatetruecolor($new_width, $new_height);
$current_image = imagecreatefromjpeg($target_path);
imagecopyresampled($result_image, $current_image, 0, 0, 0, 0, $new_width, $new_height, $current_width, $current_height);
imagejpeg($result_image, null, 100);
fclose($writing);
} else {
$target_path = "results/";
$target_path = $target_path . $a . "_cover.jpg";
move_uploaded_file($_FILES["file" . $a]["tmp_name"], $target_path);
}
However, this is what this code does for me:
1. If an image needs resizing, it just give me an image data to the browser instead of saving it to the file
2. If it doesn't need resizing, nothing happens.
What am I doing wrong?
Thanks in advance for your help!
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.
I'm using this script to create a watermark on one of client's websites the problem is that one watermark is suitable for one image and unsuitable for another.
Portrait
Landscape
Here is the script:
<?php
// this script creates a watermarked image from an image file - can be a .jpg .gif or .png file
// where watermark.gif is a mostly transparent gif image with the watermark - goes in the same directory asthis script
// where this script is named watermark.php
// call this script with an image tag
// <img src="watermark.php?path=imagepath"> where path is a relative path such as subdirectory/image.jpg
$imagesource = $_GET['path'];
$filetype = substr($imagesource,strlen($imagesource)-4,4);
$filetype = strtolower($filetype);
if($filetype == ".gif") $image = #imagecreatefromgif($imagesource);
if($filetype == ".jpg") $image = #imagecreatefromjpeg($imagesource);
if($filetype == ".png") $image = #imagecreatefrompng($imagesource);
if (!$image) die();
//This bit is the dynamic bit
if(imagesx($image) <=1100){
$watermark = #imagecreatefromgif('watermark_port.gif');
}elseif(imagesx($image) <=1600 && $imagewidth >1100){
$watermark = #imagecreatefromgif('watermark_lans.gif');
}elseif(imagesx($image) >1600){
$watermark = #imagecreatefromgif('watermark_lans.gif');
};
//End of dynamic code
$imagewidth = imagesx($image);
$imageheight = imagesy($image);
$watermarkwidth = imagesx($watermark);
$watermarkheight = imagesy($watermark);
$startwidth = (($imagewidth - $watermarkwidth)/2);
$startheight = (($imageheight - $watermarkheight)/2);
imagecopy($image, $watermark, $startwidth, $startheight, 0, 0, $watermarkwidth,
$watermarkheight);
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);
?>
However the dynamic watermark doesn't work. What i want is if the image is under 1100px wide then it uses the portrait version and if it is over that to use the landscape version instead.
Any idea would be greatly apprieciated.
Thanks,
David
What your "dynamic part" is doing is basically summed up as:
if something
do A
else if something
do B
else
do B
The middle one is completely redundant.
What you need is just:
$watermark =
imagecreatefromgif("watermark_".(imagesx($image) <= 1100 ? "port" : "lans").".gif");
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;
}
?>