i am trying to upload image and then resizing the image and save it. the upload is working fine and the resizing is also working but the resized image is not saving. if i use header ("Content-type: image/jpeg"); then it showing the resized image also. but after resizing the image is not getting saved.
here is my code:
$filename = $_FILES['myfile']['name'][$count] ;
$filename = uploadfilename($filename);
$filename1=$iiid."blog".$filename;
$target_path = "../photo/";
$target_path = $target_path . repc($filename1);
move_uploaded_file($_FILES['myfile']['tmp_name'][$count], $target_path);
$dbfield = $count+1;
$sql="update product set img_".$dbfield." ='".rep($filename1)."' where id='".$iiid."'";
$result=mysql_query($sql);
$count++;
// header ("Content-type: image/jpeg");
// print_r(get_resource_type($uploadedImage));exit();
// $resizedImage = PIPHP_ImageResize($target_path,400,400);
$w = 100;
$h = 100;
list($width, $height) = #getimagesize($target_path);
$source = #ImageCreateFromJPEG($target_path);
$resized_img = #ImageCreateTrueColor($w, $h);
#ImageCopyResampled($resized_img, $source, 0, 0, 0, 0, $w, $h, $width, $height);
#ImageJPEG($resized_img);
Related
I am trying to load an image from an external URL, then resize it and show it in a PDF. I am trying to achieve it using a single image for now, but the whole functionality will be inside a foreach loop for handling a lot of very large images.
Firstly, I resized the image, then get the contents of the image, applied base65 encoding, built up a source string from that and added the string to my img src tag. Here's my code -
$filename = 'https://jooinn.com/images/nature-319.jpg'; // URL of the image
$percent = 0.25; // percentage of resize
// 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
$imageData = base64_encode(file_get_contents($image_p));
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image_p).';base64,'.$imageData;
// Echo out a sample image
echo '<img src="' . $src . '">';
imagedestroy($image_p);
I think the problem is with this line $imageData = base64_encode(file_get_contents($image_p));, I'm doing it wrong. It works nicely with URL's but how can I make it work for a resized image here? For example, the following works perfectly as long as I don't use the resized image -
$filename = 'https://jooinn.com/images/nature-319.jpg'; // URL of the image
// Output
$imageData = base64_encode(file_get_contents($filename));
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: '.mime_content_type($filename).';base64,'.$imageData;
// Echo out a sample image
echo '<img src="' . $src . '">';
Indeed, as you said, the following line in the code is wrong:
$imageData = base64_encode(file_get_contents($image_p));
The $image_p variable is not a filename but a resource created by imagecreatetruecolor.
You first have to convert it to a jpeg file using imagejpeg().
You can avoid saving an intermediate file before encoding to base64 using the ob_*xxx* functions
ob_start();
imagejpeg($image_p);
$imageContent = ob_get_contents();
$imageData = base64_encode($imageContent);
ob_end_clean();
You also have a problem with this line, again as $image_p is not a filename:
$src = 'data: '.mime_content_type($image_p).';base64,'.$imageData;
As you are creating a jpeg file you should just replace it with:
$src = 'data: image/jpeg;base64,'.$imageData;
For convenience here is the full working script:
$filename = 'https://jooinn.com/images/nature-319.jpg'; // URL of the image
$percent = 0.25; // percentage of resize
// 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
ob_start();
imagejpeg($image_p);
$imageContent = ob_get_contents();
$imageData = base64_encode($imageContent);
ob_end_clean();
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: image/jpeg;base64,'.$imageData;
// Echo out a sample image
echo '<img src="' . $src . '">';
imagedestroy($image_p);
I'm using the following PHP function to resize big images to fit 500 px width:
<?php
function resizeImage($name) {
header('Content-type: image/jpeg');
$filename = "file.jpg";
$new_width = 500;
list($width, $height) = getimagesize($filename);
$new_height = (($height*$new_width)/$width);
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image_p, "file.jpg", 100);
}
?>
For some reason the colors on the resized image aren't exactly the same as before. They aren't as clear and strong as before. As you can see [picture removed] there's more red color and brilliance in the left (original) photo.
Why that? Is there something wrong with my script? Or is it a normal resizing effect?
This is the working code I have now:
<?php
// Call the function with: resizeImage("INSERT_YOUR_FILE_NAME_INCLUDING_SUFFIX_HERE");
function resizeImage($file_name) {
// File is located at: files/original/
$filename = "files/original/".$file_name;
// The width you want the converted image has
$new_width = 500;
// Calculate right height
list($width, $height) = getimagesize($filename);
$new_height = (($height*$new_width)/$width);
// Get image
$small = new Imagick($filename);
// Resize image, but only if original image is wider what the wanted 500 px
if($width > $new_width) {$small->resizeImage($new_width, $new_height, Imagick::FILTER_LANCZOS, 1);}
// Some code to correct the color profile
$version = $small->getVersion();
$profile = "sRGB_IEC61966-2-1_no_black_scaling.icc";
if((is_array($version) === true) && (array_key_exists("versionString", $version) === true)) {$version = preg_replace("~ImageMagick ([^-]*).*~", "$1", $version["versionString"]);if(is_file(sprintf("/usr/share/ImageMagick-%s/config/sRGB.icm", $version)) === true) {$profile = sprintf("/usr/share/ImageMagick-%s/config/sRGB.icm", $version);}}if(($srgb = file_get_contents($profile)) !== false){$small->profileImage("icc", $srgb);$small->setImageColorSpace(Imagick::COLORSPACE_SRGB);}
// Safe the image to: files/small/
$small->writeImage("files/small/".$file_name);
// Clear all resources associated to the Imagick object
$small->clear();
}
?>
Don't forget to either download the icc file from http://www.color.org/sRGB_IEC61966-2-1_no_black_scaling.icc and save it in the same directory as your resize file or change $profile = "sRGB_IEC61966-2-1_no_black_scaling.icc"; to $profile = "http://www.color.org/sRGB_IEC61966-2-1_no_black_scaling.icc";!
This script below works fine to handle an uploaded image and resize it so that the max height or width (whichever side is longer) is 200px. So it could be 200x200 if it's perfect square image, or 200x140, or 140x200, etc.
if(isset($_FILES['image'])) {
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
//checking if image exists for this pool and removing if so, before adding new image in its place
if(file_exists("uploads/".$poolid.".png")) {
unlink("uploads/".$poolid.".png");
}
// checks valid format
if(in_array($ext, $valid_extensions)) {
//re-size the image and make it a PNG before sending to server
$final_image = $poolid . ".png";
$path = "uploads/".strtolower($final_image);
$size = getimagesize($tmp);
$ratio = $size[0]/$size[1]; // width/height
if( $ratio > 1) {
$width = 200;
$height = 200/$ratio;
}
else {
$width = 200*$ratio;
$height = 200;
}
$src = imagecreatefromstring(file_get_contents($tmp));
$dst = imagecreatetruecolor($width,$height);
imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst, $path); // adjust format as needed
imagedestroy($dst);
$_SESSION['image_uploaded']="yes";
echo $path ."?".rand(1,32000);
} else {
echo 'invalid file';
}
}
Now, Facebook sharing using OpenGraph requires an image to be at least 200x200. So a 140x200 image wouldn't work with their sharing functionality.
I don't love non-square images anyway, so I would like to take the image and if it's not already a square, I'd like to add whitespace to the sides (or on the top/bottom) and save it as a perfect 200x200 square every single time.
I tried this below, but it's not working (no image gets created at all). What is wrong with what I tried to do? This doesn't seem overly complicated but clearly I'm missing something.
if(isset($_FILES['image'])) {
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
//checking if image exists for this pool and removing if so, before adding new image in its place
if(file_exists("uploads/".$poolid.".png")) {
unlink("uploads/".$poolid.".png");
}
// checks valid format
if(in_array($ext, $valid_extensions)) {
//re-size the image and make it a PNG before sending to server
$final_image = $poolid . ".png";
$path = "uploads/".strtolower($final_image);
$size = getimagesize($tmp);
$ratio = $size[0]/$size[1]; // width/height
if( $ratio > 1) {
$width = 200;
$height = 200/$ratio;
}
else {
$width = 200*$ratio;
$height = 200;
}
$src = imagecreatefromstring(file_get_contents($tmp));
$dst = imagecreatetruecolor($width,$height);
$orig_img=imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
imagedestroy($src);
// create new image and fill with background colour
$new_img = imagecreatetruecolor($output_w, $output_h);
$bgcolor = imagecolorallocate($new_img, 255, 0, 0); // red
imagefill($new_img, 0, 0, $bgcolor); // fill background colour
// copy and resize original image into center of new image
$final_img=imagecopyresampled($new_img, $orig_img, 0, 0, 0, 0, 200, 200, $width, $height);
imagepng($final_img, $path); // adjust format as needed
imagedestroy($dst);
$_SESSION['image_uploaded']="yes";
echo $path ."?".rand(1,32000);
} else {
echo 'invalid file';
}
}
You don't need a temporary intermediate image. You can paste the resampled source image right into the destination image after you fill it with background. See here:
$src = imagecreatefromstring(file_get_contents($tmp));
// Create new image and fill it with background color
$dst = imagecreatetruecolor($output_w,$output_h);
$bgcolor = imagecolorallocate($dst, 255, 0, 0);
imagefill($dst, 0, 0, $bgcolor);
// Copy resampled src image into dst
if ($ratio > 1)
imagecopyresampled($dst, $src, 0, ($output_h - $height) / 2, 0, 0, $width, $height, $size[0], $size[1]);
else
imagecopyresampled($dst, $src, ($output_w - $width) / 2, 0, 0, 0, $width, $height, $size[0], $size[1]);
imagepng($dst, $path); // adjust format as needed
imagedestroy($src);
imagedestroy($dst);
I have a code to upload an image, then creates thumbnail on the fly for this uploaded image.
The following code that creates the thumbnail (thumb.php).
$fileName = filter_input(INPUT_GET, 'src');
$width = filter_input(INPUT_GET, 'width', FILTER_SANITIZE_NUMBER_INT);
$height = filter_input(INPUT_GET, 'height', FILTER_SANITIZE_NUMBER_INT);
$im = imagecreatefromjpeg($fileName); //<=== the error message indicates to this line
$tmp_im = imagecreatetruecolor($width, $height);
$imWidth = imagesx($im);
$imHeight = imagesy($im);
imagecopyresampled($tmp_im, $im, 0, 0, 0, 0, $width, $height, $imWidth, $imHeight);
header("Content-type: image/jpeg");
imagejpeg($tmp_im);
imagedestroy($im);
imagedestroy($tmp_im);
The following code that upload the image, then implement the creation of thumbnail for the uploaded image, then display this thumbnail.
require_once ('thumb.php');
$image_dir = "images/";
if($_FILES['photo']['error'] == 0){
$fileUPloaded = $_FILES['photo']['name'];
move_uploaded_file($_FILES['photo']['tmp_name'], $image_dir.$fileUPloaded);
echo "<a href='".$image_dir.$fileUPloaded."'><img src='thumb.php?src=".$image_dir.$fileUPloaded."&width=350&height=250' alt='' /></a>";
}
Now, why appears an error Warning: imagecreatefromjpeg(): Filename cannot be empty.
Note that the image is uploaded, and was created thumbnail for uploaded image, and was displayed thumbnail. so, why that error message appear ?
//Your Image
$imgSrc = $_GET['f'];
list($width, $height) = getimagesize($imgSrc);
list($root) = explode('httpdocs', __FILE__);
$root = $root.'httpdocs';
$savePath = $root.'/_m/chacheImages/';
$savePath = '../cacheImages/';
$imgName = basename($imgSrc);
list($imgName) = explode('.', $imgName);
$fileName = $savePath.$imgName.'.jpg';
if($width > 0 && $height > 0){
$thumbSize = 100;
$img_p = imagecreatetruecolor($width, $height);
$img = imagecreatefrompng($imgSrc);
imagecopyresampled($img_p, $img, -10, 0, 0, 10, $width+30, $height, ($width), ($height-20));
//header('Content-type: image/png');
imagejpeg($img_p, $fileName);
imagedestroy($img_p);
}
I can't seem to get this to work. If i delete $fileName at imagejpeg it shows the image correctly.
But it won't save the images. What am I doing wrong?