Insert Into database upon image upload? - php

Hi i am trying to make my image upload script insert the file name as well as date_added, user_id and id into my database upon upload into the file directory.
At the moment it uploads and stores it into a file directory but i can't get it to insert into the database.
The table name is ptb_photos and the columns are id, user_id (id = user_id), file_name and date_added.
Here's my code, can someone let me know where i'm going wrong. I'm new to php and still learning so apologies if it's completely wrong.
<?php
session_start()
?>
<?
$sql=mysql_query("INSERT INTO ptb_photos SET file_name ='".addslashes($filename)."' WHERE id=".$_SESSION['user_id']." AND user_id=".$_SESSION['user_id']."");
// LOG
$log = '=== ' . #date('Y-m-d H:i:s') . ' ===============================' . "\n"
. 'FILES:' . print_r($_FILES, 1) . "\n"
. 'POST:' . print_r($_POST, 1) . "\n";
$fp = fopen('upload-log.txt', 'a');
fwrite($fp, $log);
fclose($fp);
// Result object
$r = new stdClass();
// Result content type
header('content-type: application/json');
// Maximum file size
$maxsize = 10; //Mb
// File size control
if ($_FILES['xfile']['size'] > ($maxsize * 1048576)) {
$r->error = "Max file size: $maxsize Kb";
}
// Uploading folder
$folder = 'files/';
if (!is_dir($folder))
mkdir($folder);
// If specifics folder
$folder .= $_POST['folder'] ? $_POST['folder'] . '/' : '';
if (!is_dir($folder))
mkdir($folder);
// PASS USER_ID HERE
$folder2 = '../'. '../'. 'data/'. 'photos/'. $_SESSION['user_id'] . '/';
if (!is_dir($folder2))
mkdir($folder2);
// New directory with 'files/USER_SESSION_ID/'
$folder = $newDir . $folder2;
// If the file is an image
if (preg_match('/image/i', $_FILES['xfile']['type'])) {
$filename = $_POST['value'] ? $_POST['value'] :
$folder . 'pic1.jpg';
} else {
$tld = split(',', $_FILES['xfile']['name']);
$tld = $tld[count($tld) - 1];
$filename = $_POST['value'] ? $_POST['value'] :
$folder . sha1(#microtime() . '-' . $_FILES['xfile']['name']) . $tld;
}
// Supporting image file types
$types = Array('image/png', 'image/gif', 'image/jpeg');
// File type control
if (in_array($_FILES['xfile']['type'], $types)) {
// Create an unique file name
// Uploaded file source
$source = file_get_contents($_FILES["xfile"]["tmp_name"]);
// Image resize
imageresize($source, $filename, $_POST['width'], $_POST['height'], $_POST['crop'], $_POST['quality']);
} else
// If the file is not an image
if (in_array($_FILES['xfile']['type'], $types))
move_uploaded_file($_FILES["xfile"]["tmp_name"], $filename);
// File path
$path = str_replace('upload_image_1.php', '', $_SERVER['SCRIPT_NAME']);
// Result data
$r->filename = $filename;
$r->path = $path;
$r->img = '<img src="' . $path . $filename . '" alt="image" />';
// Return to JSON
echo json_encode($r);
// Image resize function with php + gd2 lib
function imageresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80) {
$quality = $quality ? $quality : 80;
$image = imagecreatefromstring($source);
if ($image) {
// Get dimensions
$w = imagesx($image);
$h = imagesy($image);
if (($width && $w > $width) || ($height && $h > $height)) {
$ratio = $w / $h;
if (($ratio >= 1 || $height == 0) && $width && !$crop) {
$new_height = $width / $ratio;
$new_width = $width;
} elseif ($crop && $ratio <= ($width / $height)) {
$new_height = $width / $ratio;
$new_width = $width;
} else {
$new_width = $height * $ratio;
$new_height = $height;
}
} else {
$new_width = $w;
$new_height = $h;
}
$x_mid = $new_width * .5; //horizontal middle
$y_mid = $new_height * .5; //vertical middle
// Resample
error_log('height: ' . $new_height . ' - width: ' . $new_width);
$new = imagecreatetruecolor(round($new_width), round($new_height));
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
// Crop
if ($crop) {
$crop = imagecreatetruecolor($width ? $width : $new_width, $height ? $height : $new_height);
imagecopyresampled($crop, $new, 0, 0, ($x_mid - ($width * .5)), 0, $width, $height, $width, $height);
//($y_mid - ($height * .5))
}
// Output
// Enable interlancing [for progressive JPEG]
imageinterlace($crop ? $crop : $new, true);
$dext = strtolower(pathinfo($destination, PATHINFO_EXTENSION));
if ($dext == '') {
$dext = $ext;
$destination .= '.' . $ext;
}
switch ($dext) {
case 'jpeg':
case 'jpg':
imagejpeg($crop ? $crop : $new, $destination, $quality);
break;
case 'png':
$pngQuality = ($quality - 100) / 11.111111;
$pngQuality = round(abs($pngQuality));
imagepng($crop ? $crop : $new, $destination, $pngQuality);
break;
case 'gif':
imagegif($crop ? $crop : $new, $destination);
break;
}
#imagedestroy($image);
#imagedestroy($new);
#imagedestroy($crop);
}
}
?>

Try this:
$sql = mysql_query('INSERT INTO ptb_photos (file_name, id, user_id)
values ("$filename","$_SESSION[user_id]", "$_SESSION[user_id]"');
By the way, INSERT INTO syntax can never have WHERE clause, unless you're using:
INSERT INTO ... SELECT * FROM ... WHERE

Related

Cropping logic results in black image

Struggling to get the math correct for image cropping, hoping someone else is able to see my issue. It appears to be overshooting the dimensions of the image leaving 1 pixel of the original image on the left of the result.
function thumbnail_create($file, $w, $h, $crop = false, $output_filename = null, $output_dirname = null)
{
list($width, $height) = getimagesize(FILESPATH . $file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width - ($width * abs($r - $w / $h)));
} else {
$height = ceil($height - ($height * abs($r - $w / $h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w / $h > $r) {
$newwidth = $h * $r;
$newheight = $h;
} else {
$newheight = $w / $r;
$newwidth = $w;
}
}
$mime = mime_content_type(FILESPATH . $file);
$handler = "imagepng";
if (in_array($mime, ["image/gif"])) {
$src = imagecreatefromgif(FILESPATH . $file);
$handler = "imagegif";
} elseif (in_array($mime, ["image/jpeg", "image/pjpeg", "image/jpeg", "image/pjpeg"])) {
$src = imagecreatefromjpeg(FILESPATH . $file);
$handler = "imagejpeg";
} elseif (in_array($mime, ["image/png"])) {
$src = imagecreatefrompng(FILESPATH . $file);
}
if (!isset($src) || !$src) {
return false;
}
$newImage = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($newImage, false);
imagesavealpha($newImage, true);
imagecopyresampled($newImage, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
if (!empty($output_dirname)) {
make_dir($output_dirname);
}
// BUILD OUTPUT PATH/FILE
$ext = pathinfo($file, PATHINFO_EXTENSION);
if (empty($output_filename)) {
$output_filename = str_replace("." . $ext, '-thumb.' . $ext, basename($file));
}
if (empty($output_dirname)) {
$output_dirname = dirname($file);
}
$output = $output_dirname . '/' . $output_filename;
$handler($newImage, FILESPATH . $output);
return $output;
}
thumbnail_create('news/feature/fluffy-kitty.png, 100, 100, true)
Before:
After:
Original width: int(862)
Original height: int(192)
Cropped width: float(-2146)
Cropped height: int(192)

how to resize the uploading image and moving to a folder

i am trying to re size the uploading image and moving to a folder, i try with the blow code, but it is not work. i created a function for re sizing the photo, calling that function from another function, but image is not re sized, and photo is not moved to folder.
$final_save_dir = 'techpic';
$thumbname = $_FILES['tpic']['name'];
$imgName = $final_save_dir . '/' . $_FILES['tpic']['name'];
if(#move_uploaded_file($_FILES['tpic']['tmp_name'], $final_save_dir . '/' . $_FILES['tpic']['name']))
{
$this->createThumbnail($thumbname,"600","600",$final_save_dir,$final_save_dir);
}
function createThumbnail($image_name,$new_width,$new_height,$uploadDir,$moveToDir)
{
$path = $uploadDir . '/' . $image_name;
$mime = getimagesize($path);
if($mime['mime']=='image/png'){ $src_img = imagecreatefrompng($path); }
if($mime['mime']=='image/jpg'){ $src_img = imagecreatefromjpeg($path); }
if($mime['mime']=='image/jpeg'){ $src_img = imagecreatefromjpeg($path); }
if($mime['mime']=='image/pjpeg'){ $src_img = imagecreatefromjpeg($path); }
$old_x = imageSX($src_img);
$old_y = imageSY($src_img);
if($old_x > $old_y)
{
$thumb_w = $new_width;
$thumb_h = $old_y*($new_height/$old_x);
}
if($old_x < $old_y)
{
$thumb_w = $old_x*($new_width/$old_y);
$thumb_h = $new_height;
}
if($old_x == $old_y)
{
$thumb_w = $new_width;
$thumb_h = $new_height;
}
$dst_img = ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
// New save location
$new_thumb_loc = $moveToDir . $image_name;
if($mime['mime']=='image/png'){ $result = imagepng($dst_img,$new_thumb_loc,8); }
if($mime['mime']=='image/jpg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
if($mime['mime']=='image/jpeg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
if($mime['mime']=='image/pjpeg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
imagedestroy($dst_img);
imagedestroy($src_img);
return $result;
}
function img($field = 'image', $width = null, $height = null, $crop = false, $alt = null, $turl = null) {
global $editormode;
$val = $field;
if (!$val)
$val = 'no-image.png';
$alt = ($alt) ? $alt : stem(basename($val));
if ($width == null && $height == null)
$imgf = get_dir() . $val;
else
$imgf = gen_img($val, $width, $height, $crop);
if (!$imgf)
return "";
$url = $imgf;
if (!$turl)
return "<img src='$url' alt='$alt'/>\n";
else
return "<a href='$turl'><img src='$url' alt='$alt'/></a>";
}
function get_dir() {
return "upload/";
}
function gen_img($fileval, $width, $height, $crop) {
if (!$fileval)
return null;
$fname = get_dir() . $fileval;
if (!is_readable($fname))
return null;
$stem = stem(basename($fname));
if ($width != null && $height != null) {
$sz = getimagesize($fname);
if ($sz[0] == $width && $sz[1] == $height) {
return substr($fname, strlen(UPLOADROOT));
}
$sep = ($crop) ? '__' : '_';
$outname = thumb_dir($fname) . $stem . $sep . $width . "x" . $height . "." . suffix($fname);
if (!is_readable($outname) || filemtime($outname) < filemtime($fname))
createthumb($fname, $outname, $width, $height, $crop);
}
else if ($width != null && $height == null) {
$outname = thumb_dir($fname) . $stem . "_" . $width . "." . suffix($fname);
if (!is_readable($outname) || filemtime($outname) < filemtime($fname))
createthumb($fname, $outname, $width, $crop);
} else
$outname = $fname;
//echo $outname; die();
return $outname;
}
function thumb_dir($path) {
$enddir = strrpos($path, "/");
$dir = substr($path, 0, $enddir) . "/.thumbnails/";
if (!file_exists($dir))
mkdir($dir, 0777, true);
return $dir;
}
function createthumb($source, $dest, $new_w, $new_h = null, $crop = false) {
if (!file_exists($source))
return null;
$src_img = 0;
$src_img = image_create($source);
$old_w = imageSX($src_img);
$old_h = imageSY($src_img);
$x = $y = 0;
if ($new_h == null) { // we want a square thumb, cropped if necessary
if ($old_w > $old_h) {
$x = ceil(($old_w - $old_h) / 2);
$old_w = $old_h;
} else if ($old_h > $old_w) {
$y = ceil(($old_h - $old_w) / 2);
$old_h = $old_w;
}
$thumb_w = $thumb_h = $new_w;
} else if ($crop) {
$thumb_w = $new_w;
$thumb_h = $new_h;
$oar = $old_w / $old_h;
$nar = $new_w / $new_h;
if ($oar < $nar) {
$y = ($old_h - $old_h * $oar / $nar) / 2;
$old_h = ($old_h * $oar / $nar);
} else {
$x = ($old_w - $old_w * $nar / $oar) / 2;
$old_w = ($old_w * $nar / $oar);
}
} else if ($new_w * $old_h / $old_w <= $new_h) { // retain aspect ratio, limit by new_w
$thumb_h = $new_w * $old_h / $old_w;
$thumb_w = $new_w;
} else { // retain aspect ratio, limit by new_h
$thumb_w = $new_h * $old_w / $old_h;
$thumb_h = $new_h;
}
$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
imagecolortransparent($dst_img, imagecolorallocatealpha($dst_img, 0, 0, 0, 127));
imagealphablending($dst_img, false);
imagesavealpha($dst_img, true);
imagecopyresampled($dst_img, $src_img, 0, 0, $x, $y, $thumb_w, $thumb_h, $old_w, $old_h);
image_save($dst_img, $dest);
imagedestroy($dst_img);
imagedestroy($src_img);
}
function image_create($source) {
$suf = strtolower(suffix($source));
if ($source == '.jpg')
mylog("wtf", "source: $source", true);
if ($suf == "png")
return imagecreatefrompng($source);
else if ($suf == "jpg" || $suf == "jpeg")
return imagecreatefromjpeg($source);
else if ($suf == "gif")
return imagecreatefromgif($source);
return null;
}
function image_save($dst_img, $dest) {
$suf = strtolower(suffix($dest));
if ($suf == "png")
imagepng($dst_img, $dest);
else if ($suf == "jpg" || $suf == "jpeg")
imagejpeg($dst_img, $dest);
else if ($suf == "gif")
imagegif($dst_img, $dest);
}
This your function which is put in your function file
that function has make Folder in the thumbnails in the image folder when you call the function file.
Following way to call the function when image display.
<?php echo img('pages/sample_image.jpg', 122, 81, TRUE) ?>
Here the first is path of the image and 122:means width and 81:height and True/false True:crop the image and false: only resize the image.
And define the Uploadroot in your config file this path for the image folder.
Hope this works.
Thanks.
For resizing an image in php you can use Imagick::resizeImage from this article or use this article
Of course we can use Gd library which has low overhead by recommendation of #CD001. You can find explanation of GD re sizing in this article
Edit for More Explanation
for using Imagick::resizeImage you should see this description
here is the prototype of the function:
bool Imagick::resizeImage ( int $columns , int $rows , int $filter , float $blur [, bool $bestfit = false ] )
Parameters
columns
Width of the image
rows
Height of the image
filter
Refer to the list of filter constants.
blur
The blur factor where > 1 is blurry, < 1 is sharp.
bestfit
Optional fit parameter.
If you want to use gd library here is simple source code
<?php
// File and new size
//the original image has 800x600
$filename = 'images/picture.jpg';
//the resize will be a percent of the original size
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output and free memory
//the resized image will be 400x300
imagejpeg($thumb);
imagedestroy($thumb);

Uploading image to server does not work when .jpeg is the type

I'm using this script to upload images in .jpg & .png type to the server and database but when it comes to .jpeg or .JPG it does not work, instead of placing the file in right directory with correct extension it just does this /galleri/uploads/a4b7c7fb0de9c561110c2279f24ec820jpeg.php it automaticly adds .php on the end.
What I've been trying to do is to add these lines
if ( $type == 'image/jpeg' ) { $filetype = '.jpeg'; } else { $filetype = str_replace( 'image/', '', $type ); }
if ( $type == 'image/jpeg' ) { $filetype = '.JPG'; } else { $filetype = str_replace( 'image/', '', $type ); }
but with no use..
Aside from that is there any better crop tool I can use in this case that ain't so advanced?
This is the complete script:
if(isset($_POST['addmedia'])) {
$mediatype = escape(striptags($_POST['mediatype']));
$title = escape(striptags($_POST['title']));
$video = escape(striptags($_POST['medialink']));
$date = date('Y-m-d');
if ($mediatype === 'img') {
if( !isset( $_POST['p'] ) ) { $_POST['p']= 0; }
if( $_POST['p'] == 1 ) {
$name = $_FILES['image']['name'];
$temp = $_FILES['image']['tmp_name'];
$type = $_FILES['image']['type'];
$size = $_FILES['image']['size'];
if ( $type == 'image/jpeg' ) { $filetype = '.jpg'; } else { $filetype = str_replace( 'image/', '', $type ); }
if ( $type == 'image/png' ) { $filetype = '.png'; } else { $filetype = str_replace( 'image/', '', $type ); }
$path = md5( rand(0, 1000) . rand(0, 1000) . rand(0, 1000) . rand(0, 1000) ) . $filetype;
$thumb_path = md5( rand(0, 1000) . rand(0, 1000) . rand(0, 1000) . rand(0, 1000) ) . $filetype;
$size2 = getimagesize ($temp);
$width = $size2[0];
$height = $size2[1];
$maxwidth = 1281;
$maxheight = 751;
$allowed = array('image/jpeg', 'image/png');
if( in_array( $type, $allowed ) ) {
if( $width < $maxwidth && $height < $maxheight) {
if( $size < 10485760) {
if( $width == $height ) { $case = 1;} // Square form
if( $width > $height ) { $case = 2;} // Lying form
if( $width < $height ) { $case = 3;} // Standing form
switch($case) {
case 1:
$newwidth = 280;
$newheight = 150;
break;
case 2:
$newheight = 150;
$ratio = $newheight / $height;
$newwidth = round($width * $ratio);
break;
case 3:
$newwidth = 280;
$ratio = $newwidth / $width;
$newheight = round($height * $ratio);
break;
}
switch($type) {
case 'image/jpeg':
$img = imagecreatefromjpeg( $temp );
$thumb = imagecreatetruecolor( $newwidth, $newheight );
imagecopyresized( $thumb, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
imagejpeg( $thumb, $_SERVER['DOCUMENT_ROOT'] . "/galleri/uploads/thumbs/" . $thumb_path );
break;
case 'image/png':
$img = imagecreatefrompng( $temp );
$thumb = imagecreatetruecolor( $newwidth, $newheight );
imagecopyresized( $thumb, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
imagepng( $thumb, $_SERVER['DOCUMENT_ROOT'] . "/galleri/uploads/thumbs/" . $thumb_path );
break;
}
move_uploaded_file( $temp, $_SERVER['DOCUMENT_ROOT'] . "/galleri/uploads/" . $path );
$addimg = "INSERT INTO uploads (`type`, `title`, `src`, `thumb`, `date`) VALUES ('$mediatype', '$title', '$path', '$thumb_path', '$date')";
if ($add_img = $db_connect->query($addimg)) {}
echo 'Din bild har laddats upp!';
header("Location: " . $_SERVER['HTTP_REFERER']);
} else {
echo '10MB';
}
} else {
echo 'To big in size';
}
} else {
echo '.jpg, .jpeg, .png!';
}
}
} else if ($mediatype === 'vid') {
$name = $_FILES['image']['name'];
$temp = $_FILES['image']['tmp_name'];
$size = $_FILES['image']['size'];
$thumb_path = md5( rand(0, 1000) . rand(0, 1000) . rand(0, 1000) . rand(0, 1000) ) . '.jpg';
move_uploaded_file( $temp, $_SERVER['DOCUMENT_ROOT'] . "/galleri/uploads/thumbs/" . $thumb_path );
$addvid = "INSERT INTO uploads (`type`, `title`, `thumb`, `videolink`, `date`) VALUES ('$mediatype', '$title', '$thumb_path', '$video', '$date')";
if ($add_vid = $db_connect->query($addvid)) {}
echo 'Video uploaded';
header("Location: " . $_SERVER['HTTP_REFERER']);
}
}
Try this :
<?php
...
$name = $_FILES['image']['name'];
$temp = $_FILES['image']['tmp_name'];
$size = $_FILES['image']['size'];
$type = image_type_to_mime_type(exif_imagetype($temp)); // get the real image mime type
if ( $type == 'image/jpeg' ) { // jpeg
$filetype = '.jpg';
} else if ( $type == 'image/png' ){ // png
$filetype = '.png';
} else { // other image type
$filetype = '.' . str_replace( 'image/', '', $type ); // to get .gif for a gif image, for example
}
...
?>

Unable to create thumb, image is black

Am uploading Multiple image from single input and create thumb form all uploaded image on fly But when i run code i get only black image but orginal image is same as uploaded
<?php
$newname = md5(rand() * time());
$file1 = isset($_FILES['files']['name'][0]) ? $_FILES['files']['name'][0] : null;
$file2 = isset($_FILES['files']['name'][1]) ? $_FILES['files']['name'][1] : null;
$file3 = isset($_FILES['files']['name'][2]) ? $_FILES['files']['name'][2] : null;
$file4 = isset($_FILES['files']['name'][3]) ? $_FILES['files']['name'][3] : null;
$file5 = isset($_FILES['files']['name'][4]) ? $_FILES['files']['name'][4] : null;
if (isset($_FILES['files'])) {
$errors = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$file_name = $key . $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "user_data/";
if (empty($errors) == true) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if (is_dir("$desired_dir/" . $file_name) == false) {
move_uploaded_file($file_tmp, "$desired_dir/" . $newname . $file_name);
} else { // rename the file if another one exist
$new_dir = "$desired_dir/" . $newname . $file_name;
rename($file_tmp, $new_dir);
}
} else {
print_r($errors);
}
}
if (empty($error)) {
echo "FILE : $file1<br>";
echo "FILE : $file2<br>";
echo "FILE : $file3<br>";
echo "FILE : $file4<br>";
echo "FILE : $file5<br>";
}
}
$orig_directory = "$desired_dir"; //Full image folder
$thumb_directory = "thumb/"; //Thumbnail folder
/* Opening the thumbnail directory and looping through all the thumbs: */
$dir_handle = #opendir($orig_directory); //Open Full image dirrectory
if ($dir_handle > 1){ //Check to make sure the folder opened
$allowed_types=array('jpg','jpeg','gif','png');
$file_type=array();
$ext='';
$title='';
$i=0;
while ($file_name = #readdir($dir_handle)) {
/* Skipping the system files: */
if($file_name=='.' || $file_name == '..') continue;
$file_type = explode('.',$file_name); //This gets the file name of the images
$ext = strtolower(array_pop($file_type));
/* Using the file name (withouth the extension) as a image title: */
$title = implode('.',$file_type);
$title = htmlspecialchars($title);
/* If the file extension is allowed: */
if(in_array($ext,$allowed_types)) {
/* If you would like to inpute images into a database, do your mysql query here */
/* The code past here is the code at the start of the tutorial */
/* Outputting each image: */
$nw = 100;
$nh = 100;
$source = "$desired_dir{$file_name}";
$stype = explode(".", $source);
$stype = $stype[count($stype)-1];
$dest = "thumb/{$file_name}";
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch($stype) {
case 'gif':
$simg = imagecreatefromgif($source);
break;
case 'jpg':
$simg = imagecreatefromjpeg($source);
break;
case 'png':
$simg = imagecreatefrompng($source);
break;
}
$dimg = imagecreatetruecolor($nw, $nh);
$wm = $w/$nw;
$hm = $h/$nw;
$h_height = $nh/2;
$w_height = $nw/2;
if($w> $h) {
$adjusted_width = $w / $hm;
$half_width = $adjusted_width / 2;
$int_width = $w / $hm;
imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
} else {
imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
}
imagejpeg($dimg,$dest,100);
}
}
/* Closing the directory */
#closedir($dir_handle);
}
?>
When i run code this how am getting out put file, don't know whats going on can some one help me find the error
Black thumb is created for all type image formate
When i remove the following code from above code it works what does this code does
if($w> $h) {
$adjusted_width = $w / $hm;
$half_width = $adjusted_width / 2;
$int_width = $w / $hm;
imagecopyresampled($dimg,$simg,-$int_width,0,0,0,0,$adjusted_width,$nw,$nh,$w,$h);
} else
Problem
The problem is located in the following line:
imagecopyresampled($dimg, $simg, -$int_width, 0, 0, 0, $adjusted_width, $nh, $w, $h);
Why are you using a negative value as destination's x? Your source image is actually put at the left of your target image, so your target image appears empty.
Solution
I invite you to use the following function to resize your image:
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight)
{
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);
// Determine new width / height preserving aspect ratio
$srcRatio = $srcWidth / $srcHeight;
$targetRatio = $targetWidth / $targetHeight;
if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight))
{
$imgTargetWidth = $srcWidth;
$imgTargetHeight = $srcHeight;
}
else if ($targetRatio > $srcRatio)
{
$imgTargetWidth = (int) ($targetHeight * $srcRatio);
$imgTargetHeight = $targetHeight;
}
else
{
$imgTargetWidth = $targetWidth;
$imgTargetHeight = (int) ($targetWidth / $srcRatio);
}
// Creating new image with desired size
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
// Add transparency if your reduced image does not fit with the new size
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);
// Copies image, centered to the new one (if it does not fit to it)
imagecopyresampled(
$targetImg, $img, ($targetWidth - $imgTargetWidth) / 2, // centered
($targetHeight - $imgTargetHeight) / 2, // centered
0, 0, $imgTargetWidth, $imgTargetHeight, $srcWidth, $srcHeight
);
return $targetImg;
}
Implementation
<?php
$newname = md5(rand() * time());
$file1 = isset($_FILES['files']['name'][0]) ? $_FILES['files']['name'][0] : null;
$file2 = isset($_FILES['files']['name'][1]) ? $_FILES['files']['name'][1] : null;
$file3 = isset($_FILES['files']['name'][2]) ? $_FILES['files']['name'][2] : null;
$file4 = isset($_FILES['files']['name'][3]) ? $_FILES['files']['name'][3] : null;
$file5 = isset($_FILES['files']['name'][4]) ? $_FILES['files']['name'][4] : null;
if (isset($_FILES['files']))
{
$errors = array ();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name)
{
$file_name = $key . $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_size > 2097152000)
{
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "user_data/";
if (empty($errors) == true)
{
if (is_dir($desired_dir) == false)
{
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if (is_dir("$desired_dir/" . $file_name) == false)
{
move_uploaded_file($file_tmp, "$desired_dir/" . $newname . $file_name);
}
else
{ // rename the file if another one exist
$new_dir = "$desired_dir/" . $newname . $file_name;
rename($file_tmp, $new_dir);
}
}
else
{
print_r($errors);
}
}
if (empty($error))
{
echo "FILE : $file1<br>";
echo "FILE : $file2<br>";
echo "FILE : $file3<br>";
echo "FILE : $file4<br>";
echo "FILE : $file5<br>";
}
$orig_directory = "$desired_dir"; //Full image folder
$thumb_directory = "thumb/"; //Thumbnail folder
/* Opening the thumbnail directory and looping through all the thumbs: */
$dir_handle = #opendir($orig_directory); //Open Full image dirrectory
if ($dir_handle > 1)
{ //Check to make sure the folder opened
$allowed_types = array ('jpg', 'jpeg', 'gif', 'png');
$file_type = array ();
$ext = '';
$title = '';
$i = 0;
while ($file_name = #readdir($dir_handle))
{
/* Skipping the system files: */
if ($file_name == '.' || $file_name == '..')
continue;
$file_type = explode('.', $file_name); //This gets the file name of the images
$ext = strtolower(array_pop($file_type));
/* Using the file name (withouth the extension) as a image title: */
$title = implode('.', $file_type);
$title = htmlspecialchars($title);
/* If the file extension is allowed: */
if (in_array($ext, $allowed_types))
{
/* If you would like to inpute images into a database, do your mysql query here */
/* The code past here is the code at the start of the tutorial */
/* Outputting each image: */
$nw = 100;
$nh = 100;
$source = "$desired_dir{$file_name}";
$stype = explode(".", $source);
$stype = $stype[count($stype) - 1];
$dest = "thumb/{$file_name}";
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch ($stype)
{
case 'gif':
$simg = imagecreatefromgif($source);
break;
case 'jpg':
$simg = imagecreatefromjpeg($source);
break;
case 'png':
$simg = imagecreatefrompng($source);
break;
}
$dimg = resizePreservingAspectRatio($simg, $nw, $nh);
imagepng($dimg, $dest);
}
}
/* Closing the directory */
#closedir($dir_handle);
}
}
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight)
{
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);
// Determine new width / height preserving aspect ratio
$srcRatio = $srcWidth / $srcHeight;
$targetRatio = $targetWidth / $targetHeight;
if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight))
{
$imgTargetWidth = $srcWidth;
$imgTargetHeight = $srcHeight;
}
else if ($targetRatio > $srcRatio)
{
$imgTargetWidth = (int) ($targetHeight * $srcRatio);
$imgTargetHeight = $targetHeight;
}
else
{
$imgTargetWidth = $targetWidth;
$imgTargetHeight = (int) ($targetWidth / $srcRatio);
}
// Creating new image with desired size
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
// Add transparency if your reduced image does not fit with the new size
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);
// Copies image, centered to the new one (if it does not fit to it)
imagecopyresampled(
$targetImg, $img, ($targetWidth - $imgTargetWidth) / 2, // centered
($targetHeight - $imgTargetHeight) / 2, // centered
0, 0, $imgTargetWidth, $imgTargetHeight, $srcWidth, $srcHeight
);
return $targetImg;
}
?>
<form method="post" enctype="multipart/form-data">
<input name="files[]" type="file"/><br/>
<input name="files[]" type="file"/><br/>
<input name="files[]" type="file"/><br/>
<input name="files[]" type="file"/><br/>
<input name="files[]" type="file"/><br/>
<input type="submit"/>
</form>
Note: I am saving as PNG, as if you want a 100x100 image using a non-square image (such as 800x600), and without breaking its aspect ratio, we should put transparency behind the unused space and JPEG do not support it.
This is my code for uploading multiple files and cropping and cropping them.
It uploads the image to a folder, then picks the image, crops it , re-uploads the cropped image and deletes the original image.
Am sure you can play around with this
This is the php code
if(isset($_POST['upload_gal']))
{
$fk_id = $_POST['fk_id'];
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_type=='image/jpeg'||$type=='image/gif'||$type=='image/bmp'||$type=='image/png')
{
$image_info = getimagesize($_FILES["files"]["tmp_name"][$key]);
$image_width = $image_info[0];
$image_height = $image_info[1];
$desired_dir="brand_images/";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0755); // Create directory if it does not exist
}
$locationing="brand_images/$file_name";
move_uploaded_file($file_tmp,$locationing);
$image = imagecreatefromstring(file_get_contents("brand_images/$file_name"));
$rand = rand(111,43943749739349343);
$filename = "brand_images/$rand-33$file_name";
if($image_width >= 840 && $image_height >= 680)
{
$thumb_width = 1200;
$thumb_height = 700;
}else{
$thumb_width = 800;
$thumb_height = 533;
}
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
imagejpeg($thumb, $filename, 80);
move_uploaded_file($tmp_name, $filename);
mysql_query("INSERT INTO gallery VALUES('','brand_images/$rand-33$file_name','$fk_id')");
echo"<script>
window.location = document.URL.replace(/#$/, '');
</script>";
}
This is the html
<form action="" enctype="multipart/form-data" method="POST">
<h3 class="no_margin-top">Upload a new image</h3>
<hr>
<input type="hidden" name="fk_id" value="<?php echo $brand->brand_id ?>">
<input name="upload_gal" type="submit" class="btn btn-sm pull-right btn-success" value="Upload">
Upload image: <input type="file" name="files[]" multiple>
<p class="text-danger top-buffer">If image is larger than 800x533, the image would be cropped</p>
</form>
The following code will solve the problem by mapping to the correct imagecreatefrom* function or throw an exception with the invalid image type.
switch(strtolower($stype)) {
case 'gif':
$simg = imagecreatefromgif($source);
break;
case 'jpg':
case 'jpeg':
$simg = imagecreatefromjpeg($source);
break;
case 'png':
$simg = imagecreatefrompng($source);
break;
default:
throw new \Exception('invalid image type :'.$stype);
break;
}
I think it's better to go for the mime type than the extension.
You'll do this:
function check_supported_type($type)
{
switch($type)
{
case "image/jpeg":
case "image/gif":
case "image/png":
return true;
default:
return false;
}
}
function GetMimeType($file)
{
//$type = mime_content_type($file); //deprecated
/* //file info -> normal method, but returns wrong values for ics files..
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$type = $filename.":".finfo_file($finfo, $filename);
finfo_close($finfo);
*/
$forbiddenChars = array('?', '*', ':', '|', ';', '<', '>');
if(strlen(str_replace($forbiddenChars, '', $file)) < strlen($file))
throw new \ArgumentException("Forbidden characters!");
$file = escapeshellarg($file);
ob_start();
$type = system("file --mime-type -b ".$file);
ob_clean();
return $type;
}
use it like this:
$file = "someimage.jpg";
$mime = GetMimeType($file);
if(check_supported_type($mime))
{
//do your image processing
}
hope this helps
EDIT:
Maybe you can take a look at my other answer: https://stackoverflow.com/a/26981319/3641016 there you'll see how to generate thumbs.
EDIT:
added the answer to your editet question:
replace:
$wm = $w/$nw;
$hm = $h/$nw;
$h_height = $nh/2;
$w_height = $nw/2;
if($w> $h) {
$adjusted_width = $w / $hm;
$half_width = $adjusted_width / 2;
$int_width = $w / $hm;
imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
} else {
imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
}
with:
if($w > $h)
{
imagecopyresampled($dimg, $simg, 0,0, ($nw / $h * $w / 2 - $nw / 2),0, $nw,$nw, $h,$h);
}
else
{
imagecopyresampled($dimg, $simg, 0,0, 0,($nw / $w * $h / 2 - $nw / 2), $nw,$nw, $w,$w);
}
and everything should be ok. (if the thumb is quadratic)

photo upload working on local host but not on server?

hi i have a photo upload script which is working fine on my local host but when i upload it to my ftp server it doesn't upload the file. any ideas why this is, i get no error or anything just doesn't upload the file.
heres my index.php file:
<div id="areas">
<input type="file" class="droparea spot" name="xfile" data-post="upload_image_1.php" data-width="90" data-height="90" data-crop="true"/>
<form id="sampleform" action="post_image_1.php" method="post">
</form>
<script>
$('#sampleform').submit(function(e){
e.preventDefault();
$.ajax({
url:$(this).attr('action'),
type:'post',
data:$(this).serialize(),
dataType:'json',
success:function(r){
$('#form-result').append(
'<div><b>Title: </b>'+r.title+'</div>'
,'<div><b>Description: </b>'+r.description+'</div>'
,'<div><b>Image/File: </b>'
+''+ r.url +''
+'</div>'
);
}
});
});
</script>
</div>
<script>
// Calling jQuery "droparea" plugin
$('.droparea').droparea({
'init' : function(result){
//console.log('custom init',result);
},
'start' : function(area){
area.find('.error').remove();
},
'error' : function(result, input, area){
$('<div class="error">').html(result.error).prependTo(area);
return 0;
//console.log('custom error',result.error);
},
'complete' : function(result, file, input, area){
if((/image/i).test(file.type)){
area.find('img').remove();
//area.data('value',result.filename);
area.append($('<img>',{'src': result.path + result.filename + '?' + Math.random()}));
}
//console.log('custom complete',result);
}
});
</script>
<!-- /development area -->
</div>
here's my post.php file:
<?php
// LOG
$log = '=== ' . #date('Y-m-d H:i:s') . ' ===============================' . "\n"
. 'FILES:' . print_r($_FILES, 1) . "\n"
. 'POST:' . print_r($_POST, 1) . "\n";
$fp = fopen('post-log.txt', 'a');
fwrite($fp, $log);
fclose($fp);
// Result object
$r = new stdClass();
// Result content type
header('content-type: application/json');
$data = $_POST['thumbnail'];
unset($_POST['thumbnail']);
if($data){
// Uploading folder
$folder = '../'. '../'. 'data/'. 'photos/'. $_SESSION['user_id'] . '/';
if (!is_dir($folder))
mkdir($folder);
// If specifics folder
$folder .= $_POST['folder'] ? $_POST['folder'] . '/' : '';
if (!is_dir($folder))
mkdir($folder);
$filename = $_POST['value'] ? $_POST['value'] :
$folder . sha1(#microtime() . '-' . $_POST['pic1']) . '.mp4';
$filename = addslashes($filename);
$sql=mysql_query('INSERT INTO ptb_photos SET file_name ="$filename",id="$_SESSION[user_id]", user_id="$_SESSION[user_id]"');
$data = split(',', $data);
file_put_contents($filename, base64_decode($data[1]));
}
die(json_encode(array_merge(array('url' => $filename), $_POST)));
?>
And lastly heres my upload.php file:
<?php
session_start()
?>
<?
// LOG
$log = '=== ' . #date('Y-m-d H:i:s') . ' ===============================' . "\n"
. 'FILES:' . print_r($_FILES, 1) . "\n"
. 'POST:' . print_r($_POST, 1) . "\n";
$fp = fopen('upload-log.txt', 'a');
fwrite($fp, $log);
fclose($fp);
// Result object
$r = new stdClass();
// Result content type
header('content-type: application/json');
// Maximum file size
$maxsize = 10; //Mb
// File size control
if ($_FILES['xfile']['size'] > ($maxsize * 1048576)) {
$r->error = "Max file size: $maxsize Kb";
}
// Uploading folder
$folder = '../'. '../'. 'data/'. 'photos/'. $_SESSION['user_id'] . '/';
if (!is_dir($folder))
mkdir($folder);
// If specifics folder
$folder .= $_POST['folder'] ? $_POST['folder'] . '/' : '';
if (!is_dir($folder))
mkdir($folder);
// PASS USER_ID HERE
$folder2 = '../'. '../'. 'data/'. 'photos/'. $_SESSION['user_id'] . '/';
if (!is_dir($folder2))
mkdir($folder2);
// New directory with 'files/USER_SESSION_ID/'
$folder = $newDir . $folder2;
// If the file is an image
if (preg_match('/image/i', $_FILES['xfile']['type'])) {
$filename = $_POST['value'] ? $_POST['value'] :
$folder . 'thumb_pic1.jpg';
} else {
$tld = split(',', $_FILES['xfile']['name']);
$tld = $tld[count($tld) - 1];
$filename = $_POST['value'] ? $_POST['value'] :
$folder . sha1(#microtime() . '-' . $_FILES['xfile']['name']) . $tld;
}
// Supporting image file types
$types = Array('image/png', 'image/gif', 'image/jpeg');
// File type control
if (in_array($_FILES['xfile']['type'], $types)) {
// Create an unique file name
// Uploaded file source
$source = file_get_contents($_FILES["xfile"]["tmp_name"]);
// Image resize
imageresize($source, $filename, $_POST['width'], $_POST['height'], $_POST['crop'], $_POST['quality']);
} else
// If the file is not an image
if (in_array($_FILES['xfile']['type'], $types))
move_uploaded_file($_FILES["xfile"]["tmp_name"], $filename);
// File path
$path = str_replace('upload_image_1.php', '', $_SERVER['SCRIPT_NAME']);
// Result data
$r->filename = $filename;
$r->path = $path;
$r->img = '<img src="' . $path . $filename . '" alt="image" />';
// Return to JSON
echo json_encode($r);
// Image resize function with php + gd2 lib
function imageresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80) {
$quality = $quality ? $quality : 80;
$image = imagecreatefromstring($source);
if ($image) {
// Get dimensions
$w = imagesx($image);
$h = imagesy($image);
if (($width && $w > $width) || ($height && $h > $height)) {
$ratio = $w / $h;
if (($ratio >= 1 || $height == 0) && $width && !$crop) {
$new_height = $width / $ratio;
$new_width = $width;
} elseif ($crop && $ratio <= ($width / $height)) {
$new_height = $width / $ratio;
$new_width = $width;
} else {
$new_width = $height * $ratio;
$new_height = $height;
}
} else {
$new_width = $w;
$new_height = $h;
}
$x_mid = $new_width * .5; //horizontal middle
$y_mid = $new_height * .5; //vertical middle
// Resample
error_log('height: ' . $new_height . ' - width: ' . $new_width);
$new = imagecreatetruecolor(round($new_width), round($new_height));
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
// Crop
if ($crop) {
$crop = imagecreatetruecolor($width ? $width : $new_width, $height ? $height : $new_height);
imagecopyresampled($crop, $new, 0, 0, ($x_mid - ($width * .5)), 0, $width, $height, $width, $height);
//($y_mid - ($height * .5))
}
// Output
// Enable interlancing [for progressive JPEG]
imageinterlace($crop ? $crop : $new, true);
$dext = strtolower(pathinfo($destination, PATHINFO_EXTENSION));
if ($dext == '') {
$dext = $ext;
$destination .= '.' . $ext;
}
switch ($dext) {
case 'jpeg':
case 'jpg':
imagejpeg($crop ? $crop : $new, $destination, $quality);
break;
case 'png':
$pngQuality = ($quality - 100) / 11.111111;
$pngQuality = round(abs($pngQuality));
imagepng($crop ? $crop : $new, $destination, $pngQuality);
break;
case 'gif':
imagegif($crop ? $crop : $new, $destination);
break;
}
#imagedestroy($image);
#imagedestroy($new);
#imagedestroy($crop);
}
}
?>
<?php
if($_FILES['xfile']['name'])
{
$target_dir = '../'. '../'. 'data/'. 'photos/'. $_SESSION['user_id'] . '/';
$upload_file_name = basename( $_FILES['xfile']['name']);
$upload_file_ext = pathinfo($_FILES['xfile']['name'], PATHINFO_EXTENSION);
$target_file = $target_dir . 'pic1.jpg';
$target_file_sql = $target_dir . mysql_real_escape_string($upload_file_name . '.');
if (move_uploaded_file($_FILES['xfile']['tmp_name'], $target_file))
{
if (copy($target_file, $target_thumb))
{
}
}
}
?>
Did you CHMOD? So not CHMOD the folder to 777

Categories