I am trying to save image the same way it look on cropping tool, using the coping i got something like this X = 443 and Y = 180 and Width = 180 and height = 180, now my problem is how to send it to php to resize the original image as the image editor showed using the above information. Currently am using the below php code to resize image with and height but to add X and Y is what has been giving me problem.
<?php
function CroppedThumbnail($imagename, $path, $width, $height, $rename, $imgQuality, $ratio=false){
$url = '';
$info = pathinfo($imagename);
$newpath = $path;
$cdn_newpath = 'cdn/';
//Rename the image
if($rename == true){ $newFileName = $newpath . '/' . substr($info['filename'],0,5) . '-' . $width . 'x' . $height . '.jpeg';}
else{ $newFileName = $newpath . '/' . $imagename;}
$imageAvatar = substr($info['filename'],0,5) . '-' . $width . 'x' . $height . '.jpeg';
if(!file_exists($cdn_newpath.$newpath)){
mkdir($cdn_newpath.$newpath, 0777, true);
chmod($cdn_newpath.$newpath, 0755);
}
if(is_dir($cdn_newpath.$newpath . '/') && file_exists($cdn_newpath.$newFileName)){ return $url . $newFileName;}
else{
// Resample
if ($info['extension'] == 'jpeg' OR $info['extension'] == 'jpg'){ $image = imagecreatefromjpeg($imagename);}
else if ($info['extension'] == 'gif'){ $image = imagecreatefromgif($imagename);}
else if ($info['extension'] == 'png'){ $image = imagecreatefrompng($imagename);}
$widthx = imagesx( $image );
$heighty = imagesy( $image );
// calculate thumbnail size
if($ratio == true){
$new_width = $width;
$new_height = floor( $heighty * ( $width / $widthx ) );
$image_p = imagecreatetruecolor( $new_width, $new_height );
imagecopyresampled( $image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $widthx, $heighty );
}else{
$image_p = imagecreatetruecolor($width, $height);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $widthx, $heighty);
}
imagejpeg($image_p, $cdn_newpath.$newFileName);
return $url . $newFileName;
}
}
?>
You are facing same problem as I had faced. See below code snippet which I have extracted from my class. Some of the code will look pseudo code to you.
$trueFactorx = $original_height/$current_height;
$trueFactory = $original_width/$current_width;
// calls to my wrapper functions
$img=image_crop($img,$crop_cordinates,$trueFactorx,$trueFactory);
save_image($img,$image_type,$new_image_path);
function image_crop($img1,$crop_cordinates,$factorX,$factorY)
{
$corrdinate_array=explode(",", $crop_cordinates);
$x=$corrdinate_array[0] * $factorX;
$y=$corrdinate_array[1]* $factorY;
$height=$corrdinate_array[2]* $factorY;
$width=$corrdinate_array[3]* $factorX;
$img2 = imagecreatetruecolor($width, $height);
imagecopy($img2, $img1, 0, 0, $x, $y, $width, $height);
return $img2;
}
function save_image($img,$image_type,$new_image_path)
{
switch(strtolower($image_type))
{
case 'png':
header( 'Content-Type: image/png' );
imagepng($img,$new_image_path);
break;
case 'gif':
imagegif($img,$new_image_path);
break;
case 'jpeg':
imagejpeg($img,$new_image_path);
break;
case 'jpg':
imagejpeg($img,$new_image_path);
break;
default:
die('Unsupported File!');
}
imagedestroy($img);
}
Good Luck!
Related
I am creating a thumbnail in php for the uploaded image. The thumbnail is created and saved correctly but it is not rotating when needed. I test my code on many images but it did not work. Here is my code for creating the thumbnail and rotate it based on its exif data.
//thumb image
$maxDim = 300;
$filename = $_FILES['file']['name'];
list($width, $height, $type, $attr) = getimagesize($path.$filename);
if ( $width > $maxDim || $height > $maxDim )
{
$ext = pathinfo($filename, PATHINFO_EXTENSION); //var_dump($ext);
$target_filename = $path.'thumb_'.$filename;
$ratio = $width/$height;
if( $ratio > 1) {
$new_width = $maxDim;
$new_height = $maxDim/$ratio;
} else {
$new_width = $maxDim*$ratio;
$new_height = $maxDim;
}
$contents = file_get_contents($path.$filename);
$src = imagecreatefromstring($contents);
$dst = imagecreatetruecolor( $new_width, $new_height );
imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
imagedestroy( $src );
$exif = exif_read_data($path.$filename);
if (!empty($exif['Orientation'])) {
switch ($exif['Orientation']) {
case 3:
$dst = imagerotate($dst, 180, 0);
break;
case 6:
$dst = imagerotate($dst, 90, 0);
break;
case 8:
$dst = imagerotate($dst, -90, 0);
break;
}
}
//check src image type
if (exif_imagetype($path.$filename ) == IMAGETYPE_JPEG) {
imagejpeg($dst, $target_filename );
}
else if(exif_imagetype($path.$filename ) == IMAGETYPE_PNG){
imagepng($dst, $target_filename );
}
else if(exif_imagetype($path.$filename ) == IMAGETYPE_GIF){
imagegif($dst, $target_filename );
}
imagedestroy( $dst );
}
Could someone help me find out why this function does not work form me.
The parameters given to the function are:
$pathToImages is a full path starting with $_SERVER['DOCUMENT_ROOT']
$pathToThumbs is an URL which actually is a subfolder called "thumbs" inside $pathToImages
function createThumbs($pathToImages, $pathToThumbs) {
$dir = opendir($pathToImages);
while (false !== ($fname = readdir($dir))) {
if (is_file($pathToImages . $fname)) {
$info = pathinfo($pathToImages . $fname);
if ( strtolower($info['extension']) == 'jpg' || strtolower($info['extension']) == 'jpeg' ) {
list($width, $height, $type) = getimagesize($pathToImages . $fname);
switch ($type) {
case 1: $img = imagecreatefromgif($pathToImages . $fname);
break;
case 2: $img = imagecreatefromjpeg($pathToImages . $fname);
break;
case 3: $img = imagecreatefrompng($pathToImages . $fname);
break;
case 6: $img = imagecreatefromwbmp($pathToImages . $fname);
break;
default: $img = imagecreatefromjpeg($pathToImages . $fname);
};
$maxWidth = 164;
$maxHeight = 164;
if ($width > $height) {
$new_width = $maxWidth;
$new_height = floor($height * ($maxWidth / $imgw));
} else {
$new_height = $maxHeight;
$new_width = floor($width * ($maxHeight / $height));
};
$tmp_img = imagecreatetruecolor($new_width, $new_height);
// imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($tmp_img, $pathToThumbs . $fname);
imagedestroy($tmp_img);
imagedestroy($img);
};
};
};
closedir($dir);
}
Function looks ok for me.
Perhaps the directory of the thumbs was not created by PHP User, so your script has no rights to write data in the directory.
Try to create the /thumbs directory by PHP with
mkdir($pathToThumbs);
and use
chmod($pathToThumbs,755);
for giving the correct rights.
Otherwise please offer an error message. ;)
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.
What I am trying to do is speed up some of the time building websites since we have such a large work load. We tend to be doing the same things over and over, and for these Night Drop forms we have a small image preview below. When clicked on it will open up the PDF, but I was wondering if there is a way to automate this so the image preview will automatically be created and just take the logo and re-size it and put it on the top like below.
Is this possible? So it would start with the blank form on the left, and then take the logo.png file from the website and re-size it to the correct dimensions and put it in the top center like on the second image.
Sorry if this is a stupid question, just would be awesome if it could work!
Thanks :-)
I got it to work! Here is the code for anyone interested.
<?php
function resize($img, $w, $h, $newfilename) {
//Check if GD extension is loaded
if (!extension_loaded('gd') && !extension_loaded('gd2')) {
trigger_error("GD is not loaded", E_USER_WARNING);
return false;
}
//Get Image size info
$imgInfo = getimagesize($img);
switch ($imgInfo[2]) {
case 1: $im = imagecreatefromgif($img); break;
case 2: $im = imagecreatefromjpeg($img); break;
case 3: $im = imagecreatefrompng($img); break;
default: trigger_error('Unsupported filetype!', E_USER_WARNING); break;
}
//If image dimension is smaller, do not resize
if ($imgInfo[0] <= $w && $imgInfo[1] <= $h) {
$nHeight = $imgInfo[1];
$nWidth = $imgInfo[0];
}else{
//yeah, resize it, but keep it proportional
if ($w/$imgInfo[0] > $h/$imgInfo[1]) {
$nWidth = $w;
$nHeight = $imgInfo[1]*($w/$imgInfo[0]);
}else{
$nWidth = $imgInfo[0]*($h/$imgInfo[1]);
$nHeight = $h;
}
}
$nWidth = round($nWidth);
$nHeight = round($nHeight);
$newImg = imagecreatetruecolor($nWidth, $nHeight);
/* Check if this image is PNG or GIF, then set if Transparent*/
if(($imgInfo[2] == 1) OR ($imgInfo[2]==3)){
imagealphablending($newImg, false);
imagesavealpha($newImg,true);
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
}
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);
//Generate the file, and rename it to $newfilename
switch ($imgInfo[2]) {
case 1: imagegif($newImg,$newfilename); break;
case 2: imagejpeg($newImg,$newfilename); break;
case 3: imagepng($newImg,$newfilename); break;
default: trigger_error('Failed resize image!', E_USER_WARNING); break;
}
return $newfilename;
}
$img = "images/logo.png"; // File image location
$newfilename = "images/dropoff_preview.png"; // New file name for thumb
$w = 45;
$h = 45;
$thumbnail = resize($img, $w, $h, $newfilename);
$image = #$HTTP_GET_VARS['image']; // Useful if using in an img tag to call images
$image = str_replace(array("/", ".."), "", $image); // Prevent abuse
$overlay = $thumbnail;
$dir = '';
// A default image for the demo...remove if you wish.
if ($image == NULL) {
$image = 'images/dropoff_blank.jpg';
}
// Find if image exists
if (!file_exists($dir . $image)) {
die("Image does not exist.");
}
// Set offset from bottom-right corner
$w_offset = 57;
$h_offset = 230;
$extension = strtolower(substr($image, strrpos($image, ".") + 1));
// Load image from file
switch ($extension)
{
case 'jpg':
$background = imagecreatefromjpeg($dir . $image);
break;
case 'jpeg':
$background = imagecreatefromjpeg($dir . $image);
break;
case 'png':
$background = imagecreatefrompng($dir . $image);
break;
case 'gif':
$background = imagecreatefromgif($dir . $image);
break;
default:
die("Image is of unsupported type.");
}
// Find base image size
$swidth = imagesx($background);
$sheight = imagesy($background);
// Turn on alpha blending
imagealphablending($background, true);
// Create overlay image
$overlay = imagecreatefrompng($dir . $overlay);
// Get the size of overlay
$owidth = imagesx($overlay);
$oheight = imagesy($overlay);
// Overlay watermark
imagecopy($background, $overlay, $swidth - $owidth - $w_offset, $sheight - $oheight - $h_offset, 0, 0, $owidth, $oheight);
// Output header and final image
header("Content-type: image/jpeg");
header("Content-Disposition: filename=" . $image);
imagejpeg($background);
// Destroy the images
imagedestroy($background);
imagedestroy($overlay);
function doResizeAndWatermark () {
$image = 'myImage.jpg';
$watermarkImage = 'logo.png';
$x = 10;
$y = 10;
$resizeWidth = '100';
$resizeHeight = '200';
$imagesize = getimagesize ( $image );
$newImage = $image;
if ( ! copy ( $image, $this->newImage ) )
die ( 'Copy Image Failed' );
$image = imagecreatefromjpeg ( $image );
$newImage = imagecreatetruecolor ( $imagesize [ 0 ], $imagesize [ 1 ] );
if ( ! imagecopyresampled ( $newImage, $image, 0, 0, 0, 0, $resizeWidth, $resizeHeight, $imagesize [ 0 ], $imagesize [ 1 ] ) ) {
die ( 'Resizing Image Faild' );
}
$tmprslt = getimagesize ( $watermarkImage );
$watermarkImageWidth = $tmprslt [ 0 ];
$watermarkImageHeight = $tmprslt [ 1 ];
$watermarkImage = imagecreatefrompng ( $watermarkImage );
if ( ! imagecopyresampled ( $image, $watermarkImage, $x, $y, 0, 0, $watermarkImageWidth, $watermarkImageWidth, $watermarkImageWidth, $watermarkImageHeight ) )
die ( 'Watermark Copy Image Failed' );
imagejpeg ( $newImage, $image, 85 );
}
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!";
}
}