PHP image upload with watermark - php

I have this code which uploads images with watermarks. The code works fine but the watermark function re-resizes all the images upload to small width and height. I want to retain the size after adding the watermark. I believe the problem is in function but I don't know how to fix it.
if(isset($_FILES)){
$file = $_FILES['image'];
$allowedExts = array('jpg','png','gif','jpeg');
$uploadsDirectory = "imgupload/";
$maxSize = 2000000;
for($i = 0; $i < count($file['name']); $i++){
$filetmpname = $file['tmp_name'][$i];
$errors = array();
$filename = $file['name'][$i];
$filetext = strtolower(end(explode('.',$filename)));
$filesize = $file['size'][$i];
$filetmpname = $file['tmp_name'][$i];
if(in_array($filetext, $allowedExts) === FALSE){
$errors[] = "Extension is not allowed";
}
if($filesize > $maxSize){
$errors[] = "File Size must be less than {$maxSize} KB";
}
if(empty($errors)){
$random = rand(0,199);
$destination = $file['name'][$i] = $uploadsDirectory. $random."_".date("d-m-Y") . "_" . $file['name'][$i];
$upload_status = move_uploaded_file($filetmpname, $destination);
if($upload_status){
$new_name = $uploadsDirectory.$random."_".date("d-m-Y") . "_" .".jpg";
if(watermark_image($destination, $new_name))
$demo_image = $new_name;
}
}
}
}
Watermark Function:
$image_path = "images/water.png";
function watermark_image($oldimage_name, $new_image_name)
{
global $image_path;
list($owidth,$oheight) = getimagesize($oldimage_name);
$width = $height = 300;
$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, 100);
imagedestroy($im);
unlink($oldimage_name);
return true;
}

You are getting the size of the existing image here:
list($owidth,$oheight) = getimagesize($oldimage_name);
$width = $height = 300;
This is where it is making the different size image:
imagecopyresampled($im, $img_src, 0, 0, 0, 0, $width, $height, $owidth, $oheight);
http://php.net/manual/en/function.imagecopyresampled.php

Related

How to set aspect ratio in below code using PHP

I tried 2 implementations, shown below. Both are working well but when I tried to mix them it is not working anymore.
$output['status']=FALSE;
set_time_limit(0);
$allowedImageType = array("image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/x-png" );
if ($_FILES['image_file_input']["error"] > 0) {
$output['error']= "File Error";
}
elseif (!in_array($_FILES['image_file_input']["type"], $allowedImageType)) {
$output['error']= "Invalid image format";
}
elseif (round($_FILES['image_file_input']["size"] / 1024) > 4096) {
$output['error']= "Maximum file upload size is exceeded";
} else {
$temp_path = $_FILES['image_file_input']['tmp_name'];
$file = pathinfo($_FILES['image_file_input']['name']);
$fileType = $file["extension"];
$photo_name = $productname.'-'.$member_id."_".time();
$fileName1 = $photo_name . '-125x125' . ".jpg";
$fileName2 = $photo_name . '-250x250' . ".jpg";
$fileName3 = $photo_name . '-500x500' . ".jpg";
$small_thumbnail_path = "uploads/large/";
createFolder($small_thumbnail_path);
$small_thumbnail = $small_thumbnail_path . $fileName1;
$medium_thumbnail_path = "uploads/large/";
createFolder($medium_thumbnail_path);
$medium_thumbnail = $medium_thumbnail_path . $fileName2;
$large_thumbnail_path = "uploads/large/";
createFolder($large_thumbnail_path);
$large_thumbnail = $large_thumbnail_path . $fileName3;
$thumb1 = createThumbnail($temp_path, $small_thumbnail,$fileType, 125, 125 );
$thumb2 = createThumbnail($temp_path, $medium_thumbnail, $fileType, 250, 250);
$thumb3 = createThumbnail($temp_path, $large_thumbnail,$fileType, 500, 500);
if($thumb1 && $thumb2 && $thumb3) {
$output['status']=TRUE;
$output['small']= $small_thumbnail;
$output['medium']= $medium_thumbnail;
$output['large']= $large_thumbnail;
}
}
echo json_encode($output);
Function File
function createFolder($path)
{
if (!file_exists($path)) {
mkdir($path, 0755, TRUE);
}
}
function createThumbnail($sourcePath, $targetPath, $file_type, $thumbWidth, $thumbHeight){
$source = imagecreatefromjpeg($sourcePath);
$width = imagesx($source);
$height = imagesy($source);
$tnumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($tnumbImage, $source, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);
if (imagejpeg($tnumbImage, $targetPath, 90)) {
imagedestroy($tnumbImage);
imagedestroy($source);
return TRUE;
} else {
return FALSE;
}
}
Aspect ratio code, which is another one I tried to mix this code. But I was unsuccessful
$fn = $_FILES['image']['tmp_name'];
$size = getimagesize($fn);
$ratio = $size[0]/$size[1]; // width/height
$photo_name = $productname.'-'.$member_id."_".time();
{
if( $ratio > 1) {
$width1 = 500;
$height1 = 500/$ratio;
}
else {
$width1 = 500*$ratio;
$height1 = 500;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor($width1,$height1);
$fileName3 = $photo_name . '-500x500' . ".jpg";
imagecopyresampled($dst,$src,0,0,0,0,$width1,$height1,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst,$fileName3); // adjust format as needed
imagedestroy($dst);
if( $ratio > 1) {
$width2 = 250;
$height2 = 250/$ratio;
}
else {
$width2 = 250*$ratio;
$height2 = 250;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor($width2,$height2);
$fileName2 = $photo_name . '-250x250' . ".jpg";
imagecopyresampled($dst,$src,0,0,0,0,$width2,$height2,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst,$fileName2); // adjust format as needed
imagedestroy($dst);
}
What I need is to save my image after resizing but in second code there is no condition check, and I can't get image upload folder path. That's why I need to merge these 2 codes.
Basically I need need to save my image in 3 size formats: 500x500,250x250 and 125x125. Width is fixed, but height is set as per aspect ratio and set upload folder and condition in second code block.
Try this thumbnail function, which takes your source image resource and thumbnail size, and returns a new image resource for the thumbnail.
function createThumbnail($src, int $width = 100, int $height = null) {
// Ensure that src is a valid gd resource
if (!(is_resource($src) && 'gd' === get_resource_type($src))) {
throw new InvalidArgumentException(
sprintf("Argument 1 of %s expected type resource(gd), %s supplied", __FUNCTION__, gettype($src))
);
}
// Extract source image width, height and aspect ratio
$source_width = imagesx($src);
$source_height = imagesy($src);
$ratio = $source_width / $source_height;
// We know that width is always supplied, and that height can be null
// We must solve height according to aspect ratio if null is supplied
if (null === $height) {
$height = round($width / $ratio);
}
// Create the thumbnail resampled resource
$thumb = imagecreatetruecolor($width, $height);
imagecopyresampled($thumb, $src, 0, 0, 0, 0, $width, $height, $source_width, $source_height);
return $thumb;
}
Given your code above, you can now use the function like this
// Get uploaded file information as you have
// Create your source resource as you have
$source = imagecreatefromstring(file_get_contents($fn));
// Create thumbnails and save + destroy
$thumb = createThumbnail($source, 500);
imagejpeg($thumb, $thumb500TargetPath, 90);
imagedestroy($thumb);
$thumb = createThumbnail($source, 250);
imagejpeg($thumb, $thumb250TargetPath, 90);
imagedestroy($thumb);
$thumb = createThumbnail($source, 125);
imagejpeg($thumb, $thumb125TargetPath, 90);
imagedestroy($thumb);
// Don't forget to destroy the source resource
imagedestroy($source);

How to add rotation of image before being uploaded?

Hey all i have seen alot of options on how to rotate the image before being uploaded but the issue i have is i am not pro and i do not understand how to implement it into my codes.
Anyone kind enough to help me out with this?
here is my function to resize image
function resize_image($oldimage_name, $new_image_name){
list($owidth,$oheight) = getimagesize($oldimage_name);
$width = 250; $height = 250;
$im = imagecreatetruecolor($width, $height);
$img_src = imagecreatefromjpeg($oldimage_name);
imagecopyresampled($im, $img_src, 0, 0, 0, 0, $width, $height, $owidth, $oheight);
imagejpeg($im, $new_image_name, 90);
imagedestroy($im);
unlink($oldimage_name);
return true;
}
Here is my upload part
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;
resize_image($tmp_name,"uploads/images/".$image_name);
$img = ''.$image_name.'';
}
And here is link to a site which has the option but i do not know how to make it work with my code.
Text

Resize, rename and upload image with PHP

I would like to resize, rename and upload an image with PHP.
So my working script is the following:
$file_name = $_FILES['HOT_Logo']['name'];
$file_tmp_name = $_FILES['HOT_Logo']['tmp_name'];
$file_target = '../../images/hotel-logos/';
$file_size = $_FILES['HOT_Logo']['size'];
// Resize
$ratio = $width/$height;
if($ratio > 1) {
$new_width = 300;
$new_height = 300/$ratio;
}
else {
$new_width = 300*$ratio;
$new_height = 300;
}
$src = imagecreatefromstring(file_get_contents($file_tmp_name));
$dst = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagedestroy($src);
imagepng($dst, $file_target.$file_name);
imagedestroy($dst);
// Rename file
$temp = explode('.', $_FILES['HOT_Logo']['name']);
$newfilename = 'new_img_name.'.end($temp);
// Upload image
if(move_uploaded_file($_FILES['HOT_Logo']['tmp_name'], $file_target.$newfilename)) {
...
}
Problem with this script is it upload two image:
The renamed image but unresized.
The non renamed image but resized.
Why ?
You are creating a image, then moving the uploaded file, which is why it's creating two files. I believe your code is supposed to be:
$file_name = $_FILES['HOT_Logo']['name'];
$file_tmp_name = $_FILES['HOT_Logo']['tmp_name'];
$file_target = '../../images/hotel-logos/';
$file_size = $_FILES['HOT_Logo']['size'];
// Resize
$ratio = $width/$height;
if($ratio > 1) {
$new_width = 300;
$new_height = 300/$ratio;
}
else {
$new_width = 300*$ratio;
$new_height = 300;
}
// Rename file
$temp = explode('.', $file_name);
$newfilename = 'new_img_name.'.end($temp);
// Upload image
if(move_uploaded_file($file_tmp_name , $file_target.$newfilename)) {
$src = imagecreatefromstring(file_get_contents($file_target.$newfilename));
$dst = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagedestroy($src);
imagepng($dst, $file_target.$newfilename);
imagedestroy($dst);
....
}

How to resize image in this PHP script?

I'm experimenting with php script via ajax which uploads an array of images from this source.
While it works excellent I'm trying to enter php code which resizes images to 120px by width or height (whichever is larger).
For my sanity please help how to update code:
$demo_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
You can install imagemagick on your server:
<?php
function resize_image($file, $w, $h, $crop=FALSE) {
$img = new Imagick($file);
if ($crop) {
$img->cropThumbnailImage($w, $h);
} else {
$img->thumbnailImage($w, $h, TRUE);
}
return $img;
}
resize_image(‘/path/to/some/image.jpg’, 150, 150);
Another way would be using the PHP-GD:
<?php
function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*($r-$w/$h)));
} else {
$height = ceil($height-($height*($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
$img = resize_image(‘/path/to/some/image.jpg’, 150, 150);
<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Output
imagejpeg($image_p, null, 100);
Find more at php.net
Well, I took an example of "promaty" from this LINK and call from loop:
<?php
$dir = "uploads/*.*";
$images = glob( $dir );
foreach( $images as $file ):
$px = 120;
$prefix = $px . "_";
$dst = "uploads/" . $prefix . basename($file);
$resized = image_resize($file, $dst, $px, $px);
echo "<img src='" . $dst . "' />";
echo "<p>" . basename($dst) . " </p>";
endforeach;
...and thanks for your time.

Resize PNG image in PHP

I'm getting a no image display when resizing PNG however the following code works for 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;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
if( $type )){
switch( $type ){
case 'image/jpeg':
$image = imagecreatefromjpeg($fileName);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagejpeg($image_p, null, 100);
break;
case 'image/png':
imagealphablending( $image_p, false );
imagesavealpha( $image_p, true );
$image = imagecreatefrompng( $fileName );
imagecopyresampled( $image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagepng($image_p, null, 100);
break;
}
}
I've put the headers in but for some reason I'm doing something wrong for png images.
Last argument in imagepng($image_p, null, 100) should be between 0 and 9.
try this:
$image = imagecreatefrompng ( $filename );
$new_image = imagecreatetruecolor ( $width, $height ); // new wigth and height
imagealphablending($new_image , false);
imagesavealpha($new_image , true);
imagecopyresampled ( $new_image, $image, 0, 0, 0, 0, $width, $height, imagesx ( $image ), imagesy ( $image ) );
$image = $new_image;
// saving
imagealphablending($image , false);
imagesavealpha($image , true);
imagepng ( $image, $filename );
see if this works
#upload de image
public function upImagem($imagem, $dir, $res, $id, $tam){
$arquivo = $imagem;
$arq_nome = $arquivo['name'];
$ext = $arquivo['type'];
$nome=$this->RenImg($arquivo, $dir, $id, $tam);
$imagem = $arquivo['tmp_name'];
if($ext=='image/jpeg'){
$img = imagecreatefromjpeg($imagem);
}
elseif($ext=='image/png'){
$img = imagecreatefrompng($imagem);
}
elseif($ext=='image/gif'){
$img = imagecreatefromgif($imagem);
}
if(($ext=='image/png') or ($ext=='image/gif')){
list($x, $y) = getimagesize($arquivo['tmp_name']);
}
elseif($ext=='image/jpeg'){
$x = imagesx($img);//original height
$y = imagesy($img);//original width
}
$altura = $res[1];
$largura = $res[0];
$nova = imagecreatetruecolor($largura,$altura);
$preto = imagecolorallocate($nova, 0, 0, 0);
if(($ext=='image/png') or ($ext=='image/gif')){
imagealphablending($nova , false);
imagesavealpha($nova , true);
}
if($ext=='image/png'){
imagecolortransparent ($nova, $preto);
imagecopymerge($img, $nova, 0, 0, 0, 0, imagesx($nova), imagesy($nova), 100);
imagecopyresized($nova,$img,0,0,0,0,$largura,$altura, $x, $y );
}
else {
imagecopyresampled($nova,$img,0,0,0,0,$largura,$altura,$x,$y);
}
if($ext=='image/jpeg'){
imagejpeg($nova,$nome,99);
}
elseif($ext=='image/gif'){
imagealphablending($nova , false);
imagesavealpha($nova , true);
imagegif($nova,$nome,99);
}
elseif($ext=='image/png'){
imagealphablending($nova , false);
imagesavealpha($nova , true);
imagepng($nova,$nome);
}
imagedestroy($img);
imagedestroy($nova);
}
#renames the image
public function RenImg($arq,$dir,$id,$tam){
$arq_nome = $arq['name'];
$arq_nome2=str_replace('.jpg','',$arq['name']);//renomeia o arquivo
$arq_nome2=str_replace('.png','',$arq_nome2);//renomeia o arquivo
$arq_nome2=str_replace('.gif','',$arq_nome2);//renomeia o arquivo
//$new_name = md5($arq_nome);
$ext = $this->getExt($arq_nome);
$nome = $dir.$id.$tam.'.jpg';//.'.'.$ext
return $nome;
}
#capture the file extension
public function getExt($arq){
$ext = pathinfo($arq, PATHINFO_EXTENSION);
return $ext;
}
This is a code i use for JPG/PNG rezise.
$imagename = "default";
if (isset ($_FILES['arquivo'])) {
$imagename = $imagename . ".jpg";
$source = $_FILES['arquivo']['tmp_name'];
$target = "images/tmp/" . $imagename;
$type = $_FILES["arquivo"]["type"];
//JPG or JPEG
if ($type == "image/jpeg" || $type == "image/jpg") {
move_uploaded_file($source, $target);
$imagepath = $imagename;
$save = "images/" . $imagepath; //Path to save the image
$file = "images/tmp/" . $imagepath; //path to orginal size image
list($width, $height) = getimagesize($file);
$modwidth = 1920;
$diff = $width / $modwidth; // Use $modheight = $idff to mantain aspect ratio
$modheight = 1080;
$tn = imagecreatetruecolor($modwidth, $modheight);
$image = imagecreatefromjpeg($file);
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
echo "<center><b><h5>Image was updated!</h5></b>";
imagejpeg($tn, $save, 100);
} elseif ($type == "image/png") { //PNG
move_uploaded_file($source, $target);
$imagepath = $imagename;
$save = "images/" . $imagepath; //Path to save the image
$file = "images/tmp/" . $imagepath; //path to orginal size image
list($width, $height) = getimagesize($file);
$modwidth = 1920;
$diff = $width / $modwidth; // Use $modheight = $idff to mantain aspect ratio
$modheight = 1080;
$tn = imagecreatetruecolor($modwidth, $modheight);
imagealphablending($tn, false);
imagesavealpha($tn, true);
$image = imagecreatefrompng($file);
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
echo "Image was updated!";
imagepng($tn, $save, 9);
} else {
echo "Error!";
}
}

Categories