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.
Related
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 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!
I've adapted this code that I found. It resizes .jpg and .png images, and maintains alpha layers.
When I resize an image, however, the reduction in file size is far more than I had anticipated. This isn't a problem for me, as I cannot see with my eyes any degradation or data loss.
What is causing the huge compression of the file, and if I ever needed to, how can I avoid it?
function thumbnail($image, $width, $height, $target) {
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);
imagealphablending($temp_image, false);
imagesavealpha($temp_image,true);
$transparent = imagecolorallocatealpha($temp_image, 255, 255, 255, 127);
imagefilledrectangle($temp_image, 0, 0, $nWidth, $nHeight, $transparent);
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($temp_image, 'img/'.$target.'.jpg');
} else {
imagepng($temp_image,'img/'.$target.'.png');
}
imagedestroy($temp_image);
//imagedestroy($thumbnail);
}
As showdev commented, both imagejpeg() and imagepng() accept a third optional parameter for the image quality. For imagejpeg() it runs from 0 to 100 and defaults to 75), for imagepng() it is from 0 to 9 and defaults to 6.
Also, 4.4Mb is a really big size for a ~2.4Mpx image. It problably contains a lot of metadata and most of it -like Photoshop thumbsnails- is not preserved when you do an imagecopyresampled() with PHP's GD library.
You should also run one of your test images through a lossless compression program like JStrip (http://davidcrowell.com/jstrip/), to check how much it weights without the bloat.
Below is my resize.php script. I needed to install the GD Library and did so but I am still having trouble gettint the image to process like it used to my old server.HERE You can see with the error reporting on there is an empty image created and the following errors display:
Warning:
getimagesize(http://stackoverflow.com/questions/19817599/../wp-content/themes/Explorable/panos/Pano__0000.jpg):
failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in
/home/go3de/public_html/wp-content/themes/Explorable/resize.php on
line 16
Warning: Division by zero in
/home/go3de/public_html/wp-content/themes/Explorable/resize.php on
line 19
Warning: Division by zero in
/home/go3de/public_html/wp-content/themes/Explorable/resize.php on
line 30
What is going wrong? PLEASE 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);
?>
How big is the image you're trying to resize? Looks like it's complaining about running out of memory?
Try allocating more memory.
You can try adding this at the very top of the page:
ini_set('memory_limit', '512M');
...and see if it works.
Figured it out! I had a space before the initial <?php opening tag which caused the error! AH! sorry for being a noob!
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.