I'm receiving Images from URLs and I would like to save these images into a new directory, in three different sizes. I'm already getting the URLs here, now I just need a way to resize each image, with a specific height and width.
I dont want to resize uploaded images, only Images from a specific URL.
My code:
$content = file_get_contents('http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg');
$name = "http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg";
$parts = explode('.', $name);
$new_url = rand(0, pow(10, 5)) . '_' . time() . '.' . $parts[count($parts) - 1];
file_put_contents(DIRECTORY.'/' . $new_url , $content);
How can I do that? Thanks.
here is the solution based on imagecopyresampled (GD library) http://php.net/manual/en/function.imagecopyresampled.php
$content = file_get_contents('http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg');
$name = "http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg";
$parts = explode('.', $name);
$new_url = rand(0, pow(10, 5)) . '_' . time() . '.' . $parts[count($parts) - 1];
file_put_contents(DIRECTORY.'/' . $new_url , $content);
resizeImage($new_url, DIRECTORY.'/1_' . $new_url, 100, 100);
resizeImage($new_url, DIRECTORY.'/2_' . $new_url, 200, 200);
resizeImage($new_url, DIRECTORY.'/3_' . $new_url, 300, 300);
function resizeImage($source, $dest, $new_width, $new_height)
{
list($width, $height) = getimagesize($source);
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($source);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image_p, $dest, 100);
}
Related
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!
Here is my code :
foreach($_FILES as $key=>$photo){
if ($check[$key] == 'OK'){
$path = '../images/chevaux/' . $_POST['horseName'] . '_' . $horseID . '/' . $key . '.' . $file_extension;
$folder = '../images/chevaux/' . $_POST['horseName'] . '_' . $horseID;
if (!is_dir($folder))
{
mkdir($folder);
}
$filename = $photo['tmp_name'];
$percent = 4.08;
list($width, $height) = getimagesize($filename);
$newwidth = $width / $percent;
$newheight = $height / $percent;
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename, $path);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb, $path);
//....
All is working fine. Except that my pictures are completely black. The aim is to reduce their width and height by dividing them by 4.08. Know that uploaded image have width equal to 3264 px and height equal to 2448 px. Maybe it is too much?
imagecreatefromjpeg() takes only 1 parameter, the path to the filename (Either local path or URL). You're giving it two parameters.
This is my index.php file, i have uploaded and moved image from tmp folder to image folder and it's working properly. but now i want to trim image on display, every picture should be display of same size, i have tried lots of way but it's not working.
Need for help!!
<?php
require_once('appvars.php');
include 'db_connect.php';
$sql = "SELECT * FROM gitarwar";
$data = mysqli_query($dbc, $sql);
echo "<table>";
while ($row = mysqli_fetch_array($data))
{
echo '<tr><td>';
echo '<strong>' . $row['Score'] . '</strong><br/>';
echo '<strong>Name:</strong>' . $row['Name'] . '<br/>';
echo '<strong>Datetime:</strong>' . $row['Datetime'] . '<br/>';
echo '<img src="' .GW_UPLOADPATH . $row['Screenshot'] . '" alt="Score image" />';
echo "</tr>";
}
echo"</table>";
mysqli_close($dbc);
?>
I had a similar task before. My job was to check the image, and if it is smaller than my $newWidth or $newHeight, it added.
$imageUrl = [PATH OR URL TO YOUR IMAGE FILE];
$imageContent = file_get_contents($imageUrl);
$im = imagecreatefromstring($imageContent);
$width = imagesx($im);
$height = imagesy($im);
$newwidth = 300;
$newheight = 300;
$output = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($output, false);
$transparency = imagecolorallocatealpha($output, 0, 0, 0, 127);
imagefill($output, 0, 0, $transparency);
imagesavealpha($output, true);
imagecopymerge($output, $im, ($width < 300 ? (300 - $width) / 2 : 0), ($height < 300 ? (300 - $height) / 2 : 0), 0, 0, $width, $height, 100);
//Show the image
header('Content-Type: image/png');
imagepng($output); //You can save it with another parameter what is a path
imagedestroy($output);
imagedestroy($im);
You need to change this line:
imagecopymerge($output, $im, ($width < 300 ? (300 - $width) / 2 : 0), ($height < 300 ? (300 - $height) / 2 : 0), 0, 0, $width, $height, 100);
to your size.
It's actually not exactly what you want, but it could be a good starting point.
You can trim the image when uploading it, by using imagecreatefrom(jpeg|png|gif) function.
$file = "images/" . $_FILES['image']['name'];
$tmp_file = $_FILES['image']['tmp_name'];
$type = $_FILES['images']['type'];
if (move_uploaded_file($tmp_file, $file)) {
chmod($file, 0777);
// check the type of image, you can do this for other types too, just change the imagecreatefrom function to the type you want to save the image as
if ($type === 'image/jpeg') {
$jpeg = imagecreatefromjpeg($file);
$jpeg_width = imagesx($jpeg);
$jpeg_height = imagesy($jpeg);
$new_width = imagesx($jpeg) / 4; // Fix the width of the thumb nail images, change the width of image here
$new_height = imagesy($jpeg) / 4; // change the height of image here
//new image
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $jpeg, 0, 0, 0, 0, $new_width, $new_height, $jpeg_width, $jpeg_height);
imagejpeg($new_image, $thumb);
chmod($thumb, 0777);
}
}
I've been building a gallery in php as a learning exercise and also because I'll need one to display my wedding photos in a couple of months.
I have written a function that processes the images. It looks to see what images are in the original folder and generates a thumbnail and preview for each. It's worked fine up until now as I've been testing with small batches of images.
Now I have 24 images in the original folder it only process the first 18. I don't get any errors displayed it just seems to stop.
Function
function processImgs($previewWidth, $thumbWidth, $thumbPath, $previewPath, $originalPath) {
$images = glob($originalPath."*");
foreach($images as $image){
$path_parts = pathinfo($image);
// setup filenames
$thumbFile = $thumbPath . "thumb_" . $path_parts['filename'] . ".jpg";
$previewFile = $previewPath . "preview_" . $path_parts['filename'] . ".jpg";
// calculate new images sizes
$size = getimagesize($image);
$originalWidth = $size['0'];
$originalHeight = $size['1'];
$previewHeight = $originalHeight / ($originalWidth / $previewWidth);
$thumbHeight = $originalHeight / ($originalWidth / $thumbWidth);
//create new images
$original = imagecreatefromjpeg($image);
$preview = imagecreatetruecolor($previewWidth, $previewHeight);
$thumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($preview, $original, 0, 0, 0, 0, $previewWidth, $previewHeight, $originalWidth, $originalHeight);
imagecopyresampled($thumb, $original, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $originalWidth, $originalHeight);
// save images to their new folders
imagejpeg($preview, $previewFile);
imagejpeg($thumb, $thumbFile);
imagedestroy($original);
imagedestroy($preview);
imagedestroy($thumb);
// give some feedback when the script runs
if (file_exists($thumbFile) && file_exists($previewFile)) {
echo ". " . $path_parts['filename'] . " processed successfully.<br>";
} else {
echo ". " . $path_parts['filename'] . " <strong>failed.</strong><br>";
}
}
}
I call the function like this
processImgs(1200, 400, "thumb/", "preview/", "original/");
I don't know why it doesn't work with more files. Is there a time limit that I could be hitting? It does take a while. I'm currently building this locally on MAMP.
UPDATE
Mike was correct, the function was timing out. His solution is much more suitable.
I have now created a script that does what he suggested and it has solved the problem. Thanks for the help. I've added the script below in case it's of use to others.
$newWidth = 400;
if (isset($_GET['img'])) {
$img = $_GET['img'];
$filename = $img . ".jpg";
if (file_exists($filename)) {
$fp = fopen($filename, 'rb');
header("Content-Type: image/jpeg");
header("Content-Length: " . filesize($filename));
fpassthru($fp);
exit;
} else {
$originalFile = "../original/" . $filename;
$original = imagecreatefromjpeg($originalFile);
$size = getimagesize($originalFile);
$newHeight = $size['1'] / ( $size['0'] / $newWidth);
$new = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($new, $original, 0, 0, 0, 0, $newWidth, $newHeight, $size['0'], $size['1']);
imagejpeg($new, $filename);
imagedestroy($original);
imagedestroy($new);
$fp = fopen($filename, 'rb');
header("Content-Type: image/jpeg");
header("Content-Length: " . filesize($filename));
fpassthru($fp);
}
}
I have a class to read and output the image content, if $width is set, it will resize the image, and then output it.
If I call the function like this $image->readImage('123.jpg'); , it can output the image file correctly, but when I call $image->readImage('123.jpg', 300); to resize it, it just display a black image with resized width & height.
And I tried to replace the code from
#imagejpeg($thumb, null, 100);
to
#imagejpeg($image, null, 100);
will works~
-
protected function readImage($fileName, $width = 0)
{
if ($width <= 0) {
return #file_get_contents($this->destination . '/' . $fileName);
} else {
$imageSize = #getimagesize($this->destination . '/' . $fileName);
$actualWidth = $imageSize[0];
$actualHeigth = $imageSize[1];
if ($actualWidth <= $width) {
return #file_get_contents($this->destination . '/' . $fileName);
}
$height = (100 / ($actualWidth / $width)) * .01;
$height = #round($actualHeigth * $height);
$image = #imagecreatefromjpeg($this->destination . '/' . $fileName);
$thumb = #imagecreatetruecolor($width, $height);
#imagecopyresampled($thumb, $image, 0, 0, 0, 0, $width, $height, $actualWidth, $actualHeight);
ob_start();
#imagejpeg($thumb, null, 100);
$bits = ob_get_contents();
ob_end_clean();
return $bits;
}
}
Any experts know what happened and help me to solve it ?
Thanks.
you've been inconsistant in your spelling of $actualHeight vs $actualHeigth
if you didn't have so many # everywhere, then php would have told you this.