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!";
}
}
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 );
}
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!
I have a method to resize image, that accepts image string and new dimensions and should return new image string. But it doesn't work
public function putBase64ThumbToFile($base64String){
$fs = new Filesystem();
$TEMP_FOLDER_NAME = "tmpimageupload";
$pos = strpos($base64String, ';');
$type = explode('/', substr($base64String, 0, $pos))[1];
$base64String = str_replace('data:image/'. $type .';base64,', '', $base64String);
$base64String = str_replace(' ', '+', $base64String);
$data = base64_decode($base64String);
$resizedImage = $this->resizeAndCompressImage($data, 100, 100);
$fs->mkdir($TEMP_FOLDER_NAME, 0700);
$tempFilePath = $TEMP_FOLDER_NAME.'/'.uniqid() . '.' . $type;
file_put_contents($tempFilePath, $resizedImage);
}
public function resizeAndCompressImage($data, $w, $h) {
list($width, $height) = getimagesizefromstring($data);
$r = $width / $height;
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
$src = imagecreatefromstring($data);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
ob_start();
imagepng($src);
$image = ob_get_clean();
return $image;
}
In the result I get same unresized image.
You mistake is on this line:
imagepng($src);
you take the source image and not the destination image:
imagepng($dst);
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
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.