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')");
}
}
}
}
}
Related
This is my code, for resize test/15378596684270_1.jpg from 136x136px to 48x48px but when test code , its' not resize any image how can i do ?
<?PHP
session_start();
include("connect.php");
$file = "test/15378596684270_1.jpg";
list($width, $height) = getimagesize($file);
$newwidth = "48";
$newheight = "48";
$image_info = getimagesize($file);
if ($image_info['mime'] == 'image/jpeg') {
$src = imagecreatefromjpeg($file);
} elseif ($image_info['mime'] == 'image/gif') {
$src = imagecreatefromgif($file);
} elseif ($image_info['mime'] == 'image/png') {
$src = imagecreatefrompng($file);
}
$tgt = imagecreatetruecolor(48, 48);
imagecopyresampled($tgt, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
?>
I used to do this by percentages although now I am looking to do it by Pixels instead, although after trial, the images don't seem to be resizing? And I am not sure why?
$get_resize_width = '225';
$get_resize_height = '150';
$info = getimagesize($file);
list($width, $height) = getimagesize($file);
$new_width = $get_resize_width;
$new_height = $get_resize_height;
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($file);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($file);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($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, $img_quality);
$origional_image = $file;
$compressed_image = $newfile;
I have tried adding px to the end of the variables although this doesn't seem to make a difference?
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'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
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