I've got an upload function that allows both Jpegs and PNG's. After the image is uploaded, a php file is called that handles a crop function to crop the uploaded image.
After the image is cropped, it is once again saved to the server under a new name. In this current setup, only jpegs are able to be written to the server. Anything else will draw a black image.
I was wondering How I write this code so that the crop also allows PNG's
The code that handles the crop:
$imageLocation = $_SESSION['image_location'];
$newNameOverwrite = $_SESSION['new_name'];
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$jpeg_quality = 100;
$src = $imageLocation;
list($width, $height, $type, $attr) = getimagesize($src);
$targ_w = $width;
$targ_h = $height;
$img_r = imagecreatefromjpeg($src);
$dst_r = imagecreatetruecolor($_POST[('w')], $_POST[('h')]);
$uploadLocation = 'uploads/';
$name = $uploadLocation.'resized_'.$newNameOverwrite;
imagecopy(
$dst_r, $img_r,
0, 0, $_POST['x'], $_POST['y'],
$_POST['w'], $_POST['h']
);
imagejpeg($dst_r,$name,100);
$imageCropped = $name;
$_SESSION['image_cropped'] = $imageCropped;
//Thumbnail generate
include('SimpleImage.php');
$imageThumbnail = new SimpleImage();
$imageThumbnail->load($name);
$imageThumbnail->resizeToWidth(200);
$imageThumbnail->save($uploadLocation.'resizedThumbnail_'.$newNameOverwrite);
$imageThumbnailCropped = ($uploadLocation.'resizedThumbnail_'.$newNameOverwrite);
$imageThumbnailCroppedSession = $imageThumbnailCropped;
$_SESSION['image_cropped_thumbnail'] = $imageThumbnailCroppedSession;
}
Updated code:
$imageType = $_SESSION['image_type'];
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$jpeg_quality = 100;
$src = $imageLocation;
list($width, $height, $type, $attr) = getimagesize($src);
$targ_w = $width;
$targ_h = $height;
if ($imageType == '.jpg' || $imageType == '.jpeg'){
$img_r = imagecreatefromjpeg($src);
}
if ($imageType == '.png'){
$img_r = imagecreatefrompng($src);
}
$dst_r = imagecreatetruecolor($_POST[('w')], $_POST[('h')]);
$uploadLocation = 'uploads/';
$name = $uploadLocation.'resized_'.$newNameOverwrite;
imagecopy(
$dst_r, $img_r,
0, 0, $_POST['x'], $_POST['y'],
$_POST['w'], $_POST['h']
);
var_dump($imageType);
if ($imageType == '.png'){
imagepng($dst_r,$name);
}
if ($imageType == '.jpg' || $imageType == '.jpeg'){
imagejpeg($dst_r,$name, 100);
}
$imageCropped = $name;
$_SESSION['image_cropped'] = $imageCropped;
include('SimpleImage.php');
$imageThumbnail = new SimpleImage();
$imageThumbnail->load($name);
$imageThumbnail->resizeToWidth(200);
$imageThumbnail->save($uploadLocation.'resizedThumbnail_'.$newNameOverwrite);
$imageThumbnailCropped = ($uploadLocation.'resizedThumbnail_'.$newNameOverwrite);
$imageThumbnailCroppedSession = $imageThumbnailCropped;
$_SESSION['image_cropped_thumbnail'] = $imageThumbnailCroppedSession;
}
Use PHP to determine what type of image it is, then dynamically use *_png functions instead of *_jpeg ones. IE, instead of imagecreatefromjpeg use imagecreatefrompng
Related
I have a basic image upload/compression script on my website and most images seem to work fine. Having an issue with PNG for some reason, whenever I try to add a PNG image, the actual image is uploaded but the compressed image is saved as a full black square?
I can't seem to find what could be wrong with this script? The images were saving without a filetype, so I did edit the code to upload all as JPG to try to fix the error, it did fix what they were being saved as but the black images remain the same?
Can anybody point me in the right direction here?
if(isset($_POST['upload_images'])){
if(count($_FILES['upload']['name']) > 0){
//Loop through each file
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a filepath
if($tmpFilePath != ""){
//save the filename
$shortname = $_FILES['upload']['name'][$i];
//save the url and the file
$dirname = "galleries/".$portfolio_ref."/";
$filePath = $dirname.$_FILES['upload']['name'][$i];
$new_filename = date('dmYHis').rand(100000,9999999);
$new_filename2 = $dirname.$new_filename.'.jpg';
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $new_filename2)) {
$file = $new_filename2;
$data = $filePath;
$cut_name = substr($data, strpos($data, "/") + 1);
$cut_name = explode('/',$cut_name);
$cut_name = end($cut_name);
$newfile = $dirname.'thb_'.$new_filename.'.jpg';
$info = getimagesize($file);
list($width, $height) = getimagesize($file);
$max_width = 300;
$max_height = 400;
//try max width first...
$ratio = $max_width / $width;
$new_width = $max_width;
$new_height = $height * $ratio;
//if that didn't work
if ($new_height > $max_height) {
$ratio = $max_height / $height;
$new_height = $max_height;
$new_width = $width * $ratio;
}
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($file);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($file);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($file);
elseif ($info['mime'] == 'image/jpg') $image = imagecreatefromjpeg($file);
elseif ($info['mime'] == 'image/JPEG') $image = imagecreatefromjpeg($file);
elseif ($info['mime'] == 'image/PNG') $image = imagecreatefrompng($file);
elseif ($info['mime'] == 'image/GIF') $image = imagecreatefromgif($file);
elseif ($info['mime'] == 'image/JPG') $image = imagecreatefromjpeg($file);
$image = imagecreatetruecolor($new_width, $new_height);
$photo = imagecreatefromjpeg($file);
imagecopyresampled($image, $photo, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image, $newfile, 70);
$origional_image = $file;
$compressed_image = $newfile;
$digit_date = date("dmy");
$upload_date = date("Y-m-d");
$imgid = $digit_date.$i.rand();
mysqli_query($conn,"INSERT INTO umsikzw_images (image_id,portfolio_ref,thumb_link,full_link,image_name,date) VALUES ('$imgid','$portfolio_ref','$compressed_image','$origional_image','No Information','$upload_date')");
}
}
}
}
}
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'm trying to crop my image, but when I do it shows up as the right size, but all black. I've tried at least a dozen different scripts but I can't seem to get any of them to work :(
Oh and the rotation script works fine, and all of the echos are just for testing and will be removed :D
<?php
$staffID = $_POST['u'];
$actCode = $_POST['a'];
$tempAvatar = $_POST['tempAvatar'];
$x1 = $_POST['x'];
$y1 = $_POST['y'];
$wH = $_POST['w'];
$scale = $_POST['scale'];
$angle = $_POST['angle'];
$destFolder = "../../../avatars/";
$imagePath = "tempAvatars/".$tempAvatar.".jpg";
$imagePathRot = "tempAvatars/".$tempAvatar."ROTATED.jpg";
$imagePathCropped= "tempAvatars/".$tempAvatar."CROPPED.jpg";
echo 'X1: '.$x1.'<br>Y1: '.$y1.'<br>Width/Height: '.$wH.'<br>Angle: '.$angle;
if ($angle != 0) {
$source = imagecreatefromjpeg($imagePath) or notfound();
$rotate = imagerotate($source,$angle,0);
imagejpeg($rotate, $imagePathRot);
$imagePath = $imagePathRot;
}
echo '<br>X2: '.$x2.'<br>Y2: '.$y2;
$targ_w = 300;
$jpeg_quality = 90;
$img_r = imagecreatefromjpeg($imagePath);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_w );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['w']);
imagejpeg($dst_r, $imagePathCropped, $jpeg_quality);
echo '<br><img src="'.$imagePathCropped.'">';
?>
I've a this piece of code.
It charge an image to my web server and save the name into my sql.
All works except the resize time. I found the function on http://php.net/manual/en/function.imagecopyresampled.php
Any help will be very appreciated.
Thanks.
<?php
if(isset($_FILES["AddPhoto"])) {
if ($_FILES["AddPhoto"]["error"] > 0) {
$newImgMessError = $MYCARDEDIT0058;
}
else {
$fileName = $_FILES['AddPhoto']['name'];
$tmpName = $_FILES['AddPhoto']['tmp_name'];
$fileSize = $_FILES['AddPhoto']['size']/1024;
$fileType = $_FILES['AddPhoto']['type'];
$fileExtension = end(explode(".", $fileName));
if(($fileType == "image/gif" || $fileType == "image/jpeg" || $fileType == "image/pjpeg" || $fileType == "image/png" || $fileType == "image/x-png") && $fileSize < 1000000) {
$newFileName = md5(date('u').rand(0,99)).".".$fileExtension;
$imagePath = "assets/picts/".$newFileName;
// THIS PART DO NOT WORK
// Set a maximum height and width
$width = 200;
$height = 200;
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($imagePath);
$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);
$image = imagecreatefromjpeg($imagePath);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
$imagePath = imagejpeg($image_p, null, 100);
$result = #move_uploaded_file($tmpName, $imagePath);
$request = mysql_query("SELECT ".$TypeField."Images FROM $TypeFiche WHERE $TypeId='$cardId'");
$var2 = mysql_fetch_array($request);
mysql_query("UPDATE ".$TypeFiche." SET `".$TypeField."Images`='".$var2[$TypeField.'Images'].$newFileName.",' WHERE $TypeId='$cardId'");
if (!$result) {
$newImgMessError = $INSCRIPTION0074." <b>".$fileName."</b>. ".$INSCRIPTION0075."<br />";
}
if ($result) {
$newImgMessError = $INSCRIPTION0076." <b>".$fileName."</b> ".$INSCRIPTION0077."<br />";
}
}
}
}
?>
1. You have to move the file to the new directory before you can resize it. Put your resize below this line:
$result = #move_uploaded_file($tmpName, $imagePath);
Otherwise the resize code tries to access a file which doesn't exist yet.
2. You have to write the new image as file out, so replace that line
$imagePath = imagejpeg($image_p, null, 100);
with this
imagejpeg($image_p, $imagePath, 100);
http://php.net/manual/en/function.imagejpeg.php
I have a bit of code that generates thumbnails from an uploaded image. The only problem is that it cuts portrait images off, rather than resizing the portrait image to fit the height of the thumbnail, landscape images are fine. I was wondering if anyone could help me out to change the code so it will place portrait images inside the thumbnail properly? (if that makes sense?)
Here's the code:
$setSize = 150;
$setHSize = 113;
$jpeg_quality = 75;
list($width, $height, $type, $attr) = getimagesize($origPath);
$newW = $setSize;
$newH = round( $height * ( $setSize / $width ) );
$img_r = imagecreatefromjpeg($origPath) or notfound();
$dst_r = ImageCreateTrueColor( $setSize, $setHSize );
$heightOffset = round( ($setHSize-$newH)/2 );
$white = imagecolorallocate($dst_r, 255, 255, 255);
imagefilledrectangle($dst_r, 0, 0, $setSize, $setHSize, $white);
imagecopyresampled($dst_r, $img_r, 0, $heightOffset, 0, 0, $newW, $newH, $width, $height);
header("Content-type: image/jpeg");
imagejpeg($dst_r, $thbPath, $jpeg_quality);
I just don't fully understand the way php creates images, so any help would be appreciated :)
The way you compute $newW and $newH is incorrect for what you want. You are giving preference to the width, so most landscape images will look okay, but portrait will be cut off. Try the following instead:
// assume landscape and see how things look
$newW = $setSize;
$newH = round( $height * ( $setSize / $width ) );
if ($newH > $setHSize) {
// portrait image
$newH = $setHSize;
$newW = round( $width * ( $setHSize / $height ) );
}
I hope this helps!
Hope this helps.
<?php
define('DOCROOT', $_SERVER['DOCUMENT_ROOT']);
include_once(DOCROOT."/dbc.php");
//**********************| Resize based on height
$photo_height = 350;
//**********************| Get the file from the post
$file = $_FILES['file'];
$path_thumbs = (DOCROOT."/gallery/");
$path_big = (DOCROOT."/trash/");
//**********************| Check permission
if (!is_writeable($path_thumbs)){
die ("Error: The directory <b>($path_thumbs)</b> is NOT writable");
}
if (!is_writeable($path_big)){
die ("Error: The directory <b>($path_big)</b> is NOT writable");
}
//**********************| Make sure you have a file
if (isset($file)){
$file_type = $_FILES['file']['type'];
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$getExt = explode ('.', $file_name);
$file_ext = $getExt[count($getExt)-1];
//**********************| Make new name
$rand_name = md5(time());
$rand_name= rand(0,999999999);
//**********************| See the kind of file we have
if($file_size){
if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
$new_img = imagecreatefromjpeg($file_tmp);
}
elseif($file_type == "image/x-png" || $file_type == "image/png"){
$new_img = imagecreatefrompng($file_tmp);
}
elseif($file_type == "image/gif"){
$new_img = imagecreatefromgif($file_tmp);
}
//**********************| Get the height and width
list($width, $height) = getimagesize($file_tmp);
$imgratio=$height/$width;
if ($photo_height >= $height){
//*********** Dont resize if the image is smaller then $photo_height = 350;
$newwidth = $width;
$newheight = $height;
}
elseif ($imgratio>1){
$newheight = $photo_height;
$newwidth = $photo_height/$imgratio;
}
else{
$newwidth = $photo_height;
$newheight = $photo_height*$imgratio;
}
if (function_exists(imagecreatetruecolor)){ $resized_img = imagecreatetruecolor($newwidth,$newheight); }
else{ die("Error: Please make sure you have GD library ver 2+");
}
imagecopyresampled($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
ImageJpeg ($resized_img,"$path_thumbs/$rand_name.$file_ext",'100');
ImageDestroy ($resized_img);
ImageDestroy ($new_img);
}
move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext");
$newimage = "$rand_name.$file_ext";
}
else {
echo "Sorry, there was a problem, Please try again.\n\n";
}
adaptiveResizeImage
or
adaptiveCropThumblanil
in Imagick can help you