i want to resize my images on upload i found on the web verot class.upload.php
but unfortunately it doesn't work with me , no uploads , no resizes , ..
so my question is does this api requires some sort of installations,
cause i have only uploaded class.upload.php to my server
and my function is like that
public function myImageR()
{
$foo = new Upload($_FILES['img']);
if ($foo->uploaded) {
// save uploaded image with no changes
$foo->Process('/public/images/aa/');
if ($foo->processed) {
$a = true;
} else {
$a = false;
}
// save uploaded image with a new name
$foo->file_new_name_body = 'foo';
$foo->Process('/public/images/aa/');
if ($foo->processed) {
$a = true;
} else {
$a = false;
}
// save uploaded image with a new name,
// resized to 100px wide
$foo->file_new_name_body = 'image_resized';
$foo->image_resize = true;
$foo->image_convert = gif;
$foo->image_x = 100;
$foo->image_ratio_y = true;
$foo->Process('/public/images/aa/');
if ($foo->processed) {
$a = true;
$foo->Clean();
} else {
$a = false;
}
}
}
but it it doesn't work at all i am working on localhost with xammp
You need install the GD lib... Example if you are using ubuntu:
sudo apt-get install php5-gd
Then restart the Apache
sudo /etc/init.d/apache2 restart
Anyway, I use this to resize images I use this:
To upload:
$uploaded_filename = '/www/html/picts/yourfoto.jpg';
if(isset($_FILES['your_files_field_name'])){
if (move_uploaded_file($_FILES['your_files_field_name']['tmp_name'], $uploaded_filename)) {
chmod($uploaded_filename, 0755);
return $nome; // OK
} else {
return "ERROR";
}
}
To Resize:
<?php
$w = 40; // set width
$h = 40; // set height
$path = './'; // path
$image_file = (string) filter_input(INPUT_GET, 'img');
$image_path = $path . $image_file;
$img = null;
$ext = #strtolower(end(explode('.', $image_path)));
if ($ext == 'jpeg') {
$img = imagecreatefromjpeg($image_path);
} else if ($ext == 'jpg') {
$img = imagecreatefromjpeg($image_path);
} else if ($ext == 'png') {
$img = imagecreatefrompng($image_path);
} elseif ($ext == 'gif') {
$img = imagecreatefromgif($image_path);
} elseif ($ext == 'bmp') {
$img = imagecreatefromwbmp($image_path);
} else {
exit("File type not found: " . $ext);
}
if ($img) {
$width = imagesx($img);
$height = imagesy($img);
$scale = min($w / $width, $h / $height);
if ($scale < 1) {
$new_width = floor($scale * $width);
$new_height = floor($scale * $height);
$tmp_img = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagedestroy($img);
$img = $tmp_img;
}
}
if (!$img) {
$img = imagecreate($w, $h);
imagecolorallocate($img, 204, 204, 204);
$c = imagecolorallocate($img, 153, 153, 153);
$c1 = imagecolorallocate($img, 0, 0, 0);
imageline($img, 0, 0, $w, $h, $c);
imageline($img, $w, 0, 0, $h, $c);
imagestring($img, 2, 12, 55, 'IMAGE ERROR', $c1);
}
header('Content-type: ' . 'image/png');
imagejpeg($img);
If you want to save the resized file in disk:
$file = '/www/html/picts/yourfoto.jpg';
$save = imagejpeg($img, $file); // save the file
I hope this help!
Related
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);
I am attempting to create and save a squared version (thumb) of an uploaded image file with php. My current script crops it as it should, but the image is completely black. Here is my code:
if ($_FILES['profile_pic']['type'] == "image/png") {
$is_image = true;
$newImage = imagecreatefrompng($img);
} else if ($_FILES['profile_pic']['type'] == "image/jpeg") {
$is_image = true;
$newImage = imagecreatefromjpeg($img);
} else if ($_FILES['profile_pic']['type'] == "image/gif") {
$is_image = true;
$newImage = imagecreatefromgif($img);
} else {
$is_image = false;
}
$img = $_FILES["profile_pic"]['tmp_name'];
$min_width = 100;
$min_height = 100;
$width = 0;
$height = 0;
if ($is_image) {
list($width, $height) = getimagesize($img);
}
if ($is_image && $height >= $min_height && $width >= $min_width) {
$img = $_FILES["profile_pic"]['tmp_name'];
$imgPath = "../img/profile_pics/{$member_id}.png";
// Resize
$aspect_ratio = $width / $min_width;
$new_height = $height * $aspect_ratio;
$canvas1 = imagecreatetruecolor($min_width, $new_height);
imagecopyresampled($canvas1, $newImage, 0, 0, 0, 0, $min_width, $new_height, $width, $new_height);
// Crop
$canvas2 = imagecreatetruecolor($min_width, $min_height);
imagecopyresampled($canvas2, $newImage, 0, 0, 0, 0, $min_width, $min_height, $min_width, $min_height);
imagejpeg($canvas2, $imgPath, 80);
imagedestroy($canvas1);
}
I realise that there this question has been asked before, but for some reason I can't seem to make my own script work.
You're initializing $img after you try to create it via imagecreatefrompng($img) or similar. Might be the reason why it fails.
I'm also not sure you want to save all your images into a *.png file, regardless of their source type: you might want to implement something more flexible instead.
I had the resize.php script working on my previous server/domain and when you go to it HERE you can see the division by zero error. BUT! if you go to the same script on the new domain/server HEREits a blank page with no errors which leads me to believe something is not happening like it should be. I'm a quick learner but a bit of a PHP noob. Any advice with simply resizing a php array of images and displaying them I would appreciate any help.
<?php session_start();header("Pragma: public");header("Cache-Control: max-age = 604800");
header("Expires: ".gmdate("D, d M Y H:i:s", time() + 604800)." GMT");
function thumbnail($image, $width, $height) {
if($image[0] != "/") { // Decide where to look for the image if a full path is not given
if(!isset($_SERVER["HTTP_REFERER"])) { // Try to find image if accessed directly from this script in a browser
$image = $_SERVER["DOCUMENT_ROOT"].implode("/", (explode('/', $_SERVER["PHP_SELF"], -1)))."/".$image;
} else {
$image = implode("/", (explode('/', $_SERVER["HTTP_REFERER"], -1)))."/".$image;
}
} else {
$image = $_SERVER["DOCUMENT_ROOT"].$image;
}
$image_properties = getimagesize($image);
$image_width = $image_properties[0];
$image_height = $image_properties[1];
$image_ratio = $image_width / $image_height;
$type = $image_properties["mime"];
if(!$width && !$height) {
$width = $image_width;
$height = $image_height;
}
if(!$width) {
$width = round($height * $image_ratio);
}
if(!$height) {
$height = round($width / $image_ratio);
}
if($type == "image/jpeg") {
header('Content-type: image/jpeg');
$thumb = imagecreatefromjpeg($image);
} elseif($type == "image/png") {
header('Content-type: image/png');
$thumb = imagecreatefrompng($image);
} else {
return false;
}
$temp_image = imagecreatetruecolor($width, $height);
imagecopyresampled($temp_image, $thumb, 0, 0, 0, 0, $width, $height, $image_width, $image_height);
$thumbnail = imagecreatetruecolor($width, $height);
imagecopyresampled($thumbnail, $temp_image, 0, 0, 0, 0, $width, $height, $width, $height);
if($type == "image/jpeg") {
imagejpeg($thumbnail);
} else {
imagepng($thumbnail);
}
imagedestroy($temp_image);
imagedestroy($thumbnail);
}
if(isset($_GET["h"])) { $h = $_GET["h"]; } else { $h = 0; }
if(isset($_GET["w"])) { $w = $_GET["w"]; } else { $w = 0; }
thumbnail($_GET["img"], $w, $h);
?>
I would make sure errors are turned on for debugging, check if the GD library is enabled using phpinfo(), and make sure that the directory where the thumbs are created is writable.
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.
I am doing PNG image cropping using this function. Everything is working fine, but whenever I upload the .png, the image background color is changed to black. Here is the code.
$bgimage_attribs = getimagesize($bgim_file_name);
if($filetype3=='image/gif')
{
$bgim_old = imagecreatefromgif($bgim_file_name);
}
else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))
{
$bgim_old = imagecreatefromjpeg($bgim_file_name);
}
else if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
{
$bgim_old = imagecreatefrompng($bgim_file_name);
}
$bgth_max_width =265; //for Album image
$bgth_max_height =150;
$bgratio = ($bgwidth > $bgheight) ? $bgth_max_width/$bgimage_attribs[0] : $bgth_max_height/$bgimage_attribs[1];
$bgth_width =265;//$image_attribs[0] * $ratio;
$bgth_height =150;//$image_attribs[1] * $ratio;
$bgim_new = imagecreatetruecolor($bgth_width,$bgth_height);
imageantialias($bgim_new,true);
$bgth_file_name = "partners_logs/250x150/$Attachments3";
imagecopyresampled($bgim_new,$bgim_old,0,0,0,0,$bgth_width,$bgth_height, $bgimage_attribs[0], $bgimage_attribs[1]);
if($filetype3=='image/gif')
{
imagegif($bgim_new,$bgth_file_name,100);
//$bgim_old = imagegif($bgim_file_name);
}
else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))
{
imagejpeg($bgim_new,$bgth_file_name,100);
}
else if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
{
imagepng($bgim_new,$bgth_file_name,9);
} `
even i tried like this also
/************************************Resizing the image 80*60****************/
$path3="partners_logs";
$filetype3=$_FILES["pimage"]["type"];
$bgim_file_name = $path3."/".$Attachments2;
$bgimage_attribs = getimagesize($bgim_file_name);
if($filetype3=='image/gif')
{
$bgim_old = imagecreatefromgif($bgim_file_name);
}
else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))
{
$bgim_old = imagecreatefromjpeg($bgim_file_name);
}
else if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
{
$bgim_old = imagecreatefrompng($bgim_file_name);
imageAlphaBlending($bgim_old, true);
imageSaveAlpha($bgim_old, true);
}
$bgth_max_width =265; //for Album image
$bgth_max_height =150;
$bgratio = ($bgwidth > $bgheight) ? $bgth_max_width/$bgimage_attribs[0] : $bgth_max_height/$bgimage_attribs[1];
$bgth_width =265;//$image_attribs[0] * $ratio;
$bgth_height =150;//$image_attribs[1] * $ratio;
$bgim_new = imagecreatetruecolor($bgth_width,$bgth_height);
imageantialias($bgim_new,true);
$bgth_file_name = "partners_logs/250x150/$Attachments2";
imagecopyresampled($bgim_new,$bgim_old,0,0,0,0,$bgth_width,$bgth_height, $bgimage_attribs[0], $bgimage_attribs[1]);
if($filetype3=='image/gif')
{
imagegif($bgim_new,$bgth_file_name,100);
//$bgim_old = imagegif($bgim_file_name);
}
else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))
{
imagejpeg($bgim_new,$bgth_file_name,100);
}
else if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
{
imagepng($bgim_new,$bgth_file_name,9);
//set the background color to your choice, paramters are int values of red,green and blue
imagecolorallocate($bgim_new,0xFF,0xFF,0xFF);
}
/************End Resize of 80*60*******************/
maybe this helps
Don't forget about
imagealphablending() and
imagesavealpha() if you're working
with [semi]transparent png.
<?php
$file = 'semitransparent.png'; // path to png image
$img = imagecreatefrompng($file); // open image
imagealphablending($img, true); // setting alpha blending on
imagesavealpha($img, true); // save alphablending setting (important)
found at php.net - imagecreatefrompng under User Contributed Notes
NOT tested
edit see comment
<?php
$bgim_new = imagecreatetruecolor($bgth_width,$bgth_height);
imageantialias($bgim_new,true);
imageAlphaBlending($bgim_new, true);
imageSaveAlpha($bgim_new, true);
?>
After some testing and reading througt several pnp.net comments i've got a working script
<?php
$newImageName = "PNG_transparency_copy.png";
$newWidth = 265;
$newHeight = 150;
$orgAttribs = getimagesize("PNG_transparency_demonstration_1.png");
$orginal = imagecreatefrompng("PNG_transparency_demonstration_1.png");
imagesavealpha($orginal, true);
$newPng = imagecreatetruecolor($newWidth,$newHeight);
imagealphablending($newPng, false);
$color = imagecolortransparent($newPng, imagecolorallocatealpha($newPng, 0, 0, 0, 127));
imagefill($newPng, 0, 0, $color);
imagesavealpha($newPng, true);
imagecopyresampled($newPng,$orginal,0,0,0,0,$newWidth,$newHeight, $orgAttribs[0], $orgAttribs[1]);
header("Content-type: image/png");
imagepng($newPng,$newImageName);
PNG taken from Wikipedia
Try This Function....
<?php
function CropImg($img_dst, $img_src, $dst_width = 300, $dst_height = 180){
$ext = pathinfo($img_src, PATHINFO_EXTENSION);
if($ext != 'jpg' and $ext != 'jpeg'){
$image = imagecreatefrompng($img_src);
}else{
$image = imagecreatefromjpeg($img_src);
}
$filename = $img_dst;
$thumb_width = $dst_width;
$thumb_height = $dst_height;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
if($ext == 'png'){
imagealphablending($thumb, false);
$white = imagecolorallocatealpha($thumb, 0, 0, 0, 127); //FOR WHITE BACKGROUND
imagefilledrectangle($thumb,0,0,$thumb_width,$thumb_height,$white);
imagesavealpha($thumb, true);
}
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
if($ext == 'png'){
imagepng($thumb, $filename);
}else{
imagejpeg($thumb, $filename, 80);
}
return true;
}
CropImg("photo.png", "result.png", 300, 180);
?>