Php code to create thumb not working after update - php

The following php script creates a thumb and is part of an image gallery package. Though since a php update to version 5.6, the code doesn't work anymore because the appearance of 'eregi' in a dependent file.
Does anyone knows an alternative function for 'eregi'?
<?php
include('config.inc.php');
$C_JGALL['extentions'] = "jpg|jpeg|gif|png";
if(is_dir('themes/' . $C_JGALL['gall_theme']) && file_exists('themes/' .$C_JGALL['gall_theme'] . '/' . $C_JGALL['gall_theme'] . '.css') && file_exists('themes/' . $C_JGALL['gall_theme'] . '/' . $C_JGALL['gall_theme'] . '.conf.php'))
{
include('themes/' . $C_JGALL['gall_theme'] . '/' . $C_JGALL['gall_theme'] . '.conf.php');
}
else
{
die('corrupt theme');
}
$MaxSize = $_GET['MaxSize'];
switch ($_GET['src']) {
case 'folder':
$src = $G_JGALL['inc_path'] . 'themes/' . $C_JGALL['gall_theme'] . '/images/folder.jpg';
break;
case 'question':
$src = $G_JGALL['inc_path'] . 'themes/' . $C_JGALL['gall_theme'] . '/images/no_image.jpg';
break;
default:
$src= $_GET['src'];
break;
}
function GetExtention($filename) {
$FileNameArray = explode('.',$filename);
return($FileNameArray[count($FileNameArray)-1]);
}
$ext = GetExtention($src);
$srcSize = getImageSize($src);
$srcRatio = $srcSize[0]/$srcSize[1];
$destRatio = $MaxSize/$MaxSize;
if ($destRatio > $srcRatio) {
$MaxSize = (($C_JGALL['gall_show_filenames'] != 'y') OR isset($_GET['view'])) ? $MaxSize : $MaxSize / 100 * 80;
$destSize[1] = $MaxSize;
$destSize[0] = $MaxSize*$srcRatio;
}
else {
$destSize[0] = $MaxSize;
$destSize[1] = $MaxSize/$srcRatio;
}
if(eregi($C_JGALL['extentions'],$ext) AND (substr($srcSize['mime'],0,5) == 'image'))
if(eregi("jpg|jpeg",$ext)) {
$destImage = imagecreatetruecolor($destSize[0],$destSize[1]);
$srcImage = imagecreatefromjpeg($src);
imagecopyresampled($destImage, $srcImage, 0, 0, 0, 0,$destSize[0],$destSize[1],$srcSize[0],$srcSize[1]);
imagejpeg($destImage,'',80);
}
elseif(eregi("gif",$ext)) {
$destImage = imageCreateTrueColor($destSize[0],$destSize[1]);
$srcImage = imageCreateFromGIF($src);
imageCopyResampled($destImage, $srcImage, 0, 0, 0, 0,$destSize[0],$destSize[1],$srcSize[0],$srcSize[1]);
imageGIF($destImage,'',80);
}
elseif(eregi("png",$ext)) {
$destImage = imageCreateTrueColor($destSize[0],$destSize[1]);
$srcImage = imageCreateFromPNG($src);
imageCopyResampled($destImage, $srcImage, 0, 0, 0, 0,$destSize[0],$destSize[1],$srcSize[0],$srcSize[1]);
imagePNG($destImage,'',80);
}
else {
die('ongeldige extentie of mime-type.');
}
// --> End
?>

I would look at the PHP Documentation, as you have identified already the function has been deprecated. They do however make a recommendation to replace it;
http://php.net/manual/en/function.eregi.php
TIP eregi() is deprecated as of PHP 5.3.0. preg_match() with the i (PCRE_CASELESS) modifier is the suggested alternative.

Related

CodeIgniter set image max-size to 0 and validate file type if jpg or png

Anyone can help me to set image max-size to 0.
Because I'm getting Error code: 1
Please help me to construct this code. I don't want to change the limit in php.ini Just want to know if there is a code solution for this problem:
function uploadPhoto()
{
$control = 'filephoto';
$path = './upload/';
$image = $_FILES[$control]['name'];
$size = $_FILES[$control]['size'];
if ($imageName = $this->doUpload($control, $path, $image, 'all')) {
} else {
}
}
function doUpload($control, $path, $imageName, $sizes)
{
if ($this->session->userdata('logged_in')) {
$session_data = $this->session->userdata('logged_in');
$u_id = $session_data['u_id'];
$alnum = random_string('alnum', 16);
if ( ! isset($_FILES[$control]) || ! is_uploaded_file($_FILES[$control]['tmp_name'])) {
$this->session->set_flashdata('error_nofile', 'No file was chosen Error code: ' . $_FILES[$control]['error']);
header('location:' . base_url() . "indexc/upload/");
return false;
}
if ($_FILES[$control]['size'] > 2048000) {
$this->session->set_flashdata('error_largefile', 'File is too large (' . round(($_FILES[$control]["size"] / 1000)) . 'kb), please choose a file under 2,048kb');
header('location:' . base_url() . "indexc/upload/");
return false;
}
if ($_FILES[$control]['error'] !== UPLOAD_ERR_OK) {
$this->session->set_flashdata('error_failed', 'Upload failed. Error code: ' . $_FILES[$control]['error']);
header('location:' . base_url() . "indexc/upload/");
Return false;
}
switch (strtolower($_FILES[$control]['type'])) {
case 'image/jpeg':
$image = imagecreatefromjpeg($_FILES[$control]['tmp_name']);
move_uploaded_file($_FILES[$control]["tmp_name"], $path . $imageName);
break;
case 'image/png':
$image = imagecreatefrompng($_FILES[$control]['tmp_name']);
move_uploaded_file($_FILES[$control]["tmp_name"], $path . $imageName);
break;
case 'image/gif':
$image = imagecreatefromgif($_FILES[$control]['tmp_name']);
move_uploaded_file($_FILES[$control]["tmp_name"], $path . $imageName);
break;
default:
$this->session->set_flashdata('error_notallowed', 'This file type is not allowed');
header('location:' . base_url() . "indexc/upload/");
return false;
}
#unlink($_FILES[$control]['tmp_name']);
$old_width = imagesx($image);
$old_height = imagesy($image);
//Create tn version
if ($sizes == 'tn' || $sizes == 'all') {
$max_width = 600;
$max_height = 600;
$scale = min($max_width / $old_width, $max_height / $old_height);
if ($old_width > 600 || $old_height > 600) {
$new_width = ceil($scale * $old_width);
$new_height = ceil($scale * $old_height);
} else {
$new_width = $old_width;
$new_height = $old_height;
}
$new = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
switch (strtolower($_FILES[$control]['type'])) {
case 'image/jpeg':
imagejpeg($new, $path . '' . $u_id . '_' . $alnum . '_' . $imageName, 90);
break;
case 'image/png':
imagealphablending($new, false);
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
imagesavealpha($new, true);
imagepng($new, $path . '' . $u_id . '_' . $alnum . '_' . $imageName, 0);
break;
case 'image/gif':
imagegif($new, $path . '' . $u_id . '_' . $alnum . '_' . $imageName);
break;
default:
}
}
imagedestroy($image);
imagedestroy($new);
/* print '<div style="font-family:arial;"><b>'.$imageName.'</b> Uploaded successfully. Size: '.round($_FILES[$control]['size']/1000).'kb</div>'; */
$this->session->set_flashdata('success_upload', '<div style="font-family:arial;"><b>' . $imageName . '</b> Uploaded successfully. Size: ' . round($_FILES[$control]['size'] / 1000) . 'kb</div>');
$postdata['p_u_id'] = $u_id;
$postdata['p_content'] = $this->input->post('content');
$postdata['p_image'] = $u_id . '_' . $alnum . '_' . $imageName;
$postdata['p_image_original'] = $imageName;
$postdata['p_posted'] = date("Y-m-d H:i:s");
$res = $this->indexm->postinsert_to_db($postdata);
header('location:' . base_url() . "indexc/upload/");
} else {
$this->load->view('index');
}
}
I also want to validate if the file type is jpg or png
Please help me!
thanks,
joe
try default codeigniter library :
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}

Cropping an image using php

I'm trying to crop an image when it has been uploaded. So far I've only managed to resize it but if an image is a rectangular shape then the image is squashed which doesn't look nice. I'm trying to get coding that I can use with the function that I currently have to resize. The ones that I'm seeing I have to change my function and I'm hoping not to do that.
Here is my function
function createThumbnail($filename) {
global $_SITE_FOLDER;
//require 'config.php';
$final_width_of_image = 82;
$height = 85;
$path_to_image_directory = $_SITE_FOLDER.'portfolio_images/';
$path_to_thumbs_directory = $_SITE_FOLDER.'portfolio_images/thumbs/';
if(preg_match('/[.](jpg)$/', $filename)) {
$im = imagecreatefromjpeg($path_to_image_directory . $filename);
} else if (preg_match('/[.](gif)$/', $filename)) {
$im = imagecreatefromgif($path_to_image_directory . $filename);
} else if (preg_match('/[.](png)$/', $filename)) {
$im = imagecreatefrompng($path_to_image_directory . $filename);
}
$ox = imagesx($im);
$oy = imagesy($im);
$nx = $final_width_of_image;
$ny = floor($oy * ($final_width_of_image / $ox));
//$ny = $height;
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
if(!file_exists($path_to_thumbs_directory)) {
if(!mkdir($path_to_thumbs_directory)) {
die("There was a problem. Please try again!");
}
}
imagejpeg($nm, $path_to_thumbs_directory . $filename);
$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
$tn .= '<br />Congratulations. Your file has been successfully uploaded, and a thumbnail has been created.';
echo $tn;
}
Here is my function.
<?php
function crop($file_input, $file_output, $crop = 'square',$percent = false) {
list($w_i, $h_i, $type) = getimagesize($file_input);
if (!$w_i || !$h_i) {
echo 'Unable to get the length and width of the image';
return;
}
$types = array('','gif','jpeg','png');
$ext = $types[$type];
if ($ext) {
$func = 'imagecreatefrom'.$ext;
$img = $func($file_input);
} else {
echo 'Incorrect file format';
return;
}
if ($crop == 'square') {
$min = $w_i;
if ($w_i > $h_i) $min = $h_i;
$w_o = $h_o = $min;
} else {
list($x_o, $y_o, $w_o, $h_o) = $crop;
if ($percent) {
$w_o *= $w_i / 100;
$h_o *= $h_i / 100;
$x_o *= $w_i / 100;
$y_o *= $h_i / 100;
}
if ($w_o < 0) $w_o += $w_i;
$w_o -= $x_o;
if ($h_o < 0) $h_o += $h_i;
$h_o -= $y_o;
}
$img_o = imagecreatetruecolor($w_o, $h_o);
imagecopy($img_o, $img, 0, 0, $x_o, $y_o, $w_o, $h_o);
if ($type == 2) {
return imagejpeg($img_o,$file_output,100);
} else {
$func = 'image'.$ext;
return $func($img_o,$file_output);
}
}
?>
And you can call like this
crop($file_input, $file_output, $crop = 'square',$percent = false);
And also resize function if you need.
<?php
function resize($file_input, $file_output, $w_o, $h_o, $percent = false) {
list($w_i, $h_i, $type) = getimagesize($file_input);
if (!$w_i || !$h_i) {
return;
}
$types = array('','gif','jpeg','png');
$ext = $types[$type];
if ($ext) {
$func = 'imagecreatefrom'.$ext;
$img = $func($file_input);
} else {
return;
}
if ($percent) {
$w_o *= $w_i / 100;
$h_o *= $h_i / 100;
}
if (!$h_o) $h_o = $w_o/($w_i/$h_i);
if (!$w_o) $w_o = $h_o/($h_i/$w_i);
$img_o = imagecreatetruecolor($w_o, $h_o);
imagecopyresampled($img_o, $img, 0, 0, 0, 0, $w_o, $h_o, $w_i, $h_i);
if ($type == 2) {
return imagejpeg($img_o,$file_output,100);
} else {
$func = 'image'.$ext;
return $func($img_o,$file_output);
}
}
?>
resize($file_input, $file_output, $w_o, $h_o, $percent = false);
You can use SimpleImage class found here SimpleImage
[edit] Updated version with many more features here SimleImage Updated
I use this when resizing various images to a smaller thumbnail size while maintaining aspect ratio and exact image size output. I fill the blank area with a colour that suits the background for where the image will be placed, this class supports cropping. Explore the methods cutFromCenter and maxareafill.
For example in your code you would not need to imagecreatefromjpeg() you would simply;
Include the class include('SimpleImage.php');
then;
$im = new SimpleImage();
$im->load($path_to_image_directory . $filename);
$im->maxareafill($output_width,$output_height, 0,0,0); // rgb
$im->save($path_to_image_directory . $filename);
I use this class daily and find it very versatile.

Scaling watermark on image with PHP

i am working on php function that would put watermark on image. I´ve got it working but i need to scale this watermark so the height of the watermark will be 1/3 of the original image. I can do that, but when i put it into my code it just doesnt work, because the parameter of imagecopymerge must be resource, which i dont know what means.
define('WATERMARK_OVERLAY_IMAGE', 'watermark.png');
define('WATERMARK_OVERLAY_OPACITY', 100);
define('WATERMARK_OUTPUT_QUALITY', 100);
function create_watermark($source_file_path, $output_file_path)
{
list($source_width, $source_height, $source_type) = getimagesize($source_file_path);
if ($source_type === NULL) {
return false;
}
switch ($source_type) {
case IMAGETYPE_GIF:
$source_gd_image = imagecreatefromgif($source_file_path);
break;
case IMAGETYPE_JPEG:
$source_gd_image = imagecreatefromjpeg($source_file_path);
break;
case IMAGETYPE_PNG:
$source_gd_image = imagecreatefrompng($source_file_path);
break;
default:
return false;
}
$overlay_gd_image = imagecreatefrompng(WATERMARK_OVERLAY_IMAGE);
$overlay_width = imagesx($overlay_gd_image);
$overlay_height = imagesy($overlay_gd_image);
//THIS PART IS WHAT SHOULD RESIZE THE WATERMARK
$source_width = imagesx($source_gd_image);
$source_height = imagesy($source_gd_image);
$percent = $source_height/3/$overlay_height;
// Get new sizes
$new_overlay_width = $overlay_width * $percent;
$new_overlay_height = $overlay_height * $percent;
// Load
$overlay_gd_image_resized = imagecreatetruecolor($new_overlay_width, $new_overlay_height);
// Resize
$overlay_gd_image_complet = imagecopyresized($overlay_gd_image_resized, $overlay_gd_image, 0, 0, 0, 0, $new_overlay_width, $new_overlay_height, $overlay_width, $overlay_height);
//ALIGN BOTTOM, RIGHT
if (isset($_POST['kde']) && $_POST['kde'] == 'pravo') {
imagecopymerge(
$source_gd_image,
$overlay_gd_image_complet,
$source_width - $new_overlay_width,
$source_height - $new_overlay_height,
0,
0,
$new_overlay_width,
$new_overlay_height,
WATERMARK_OVERLAY_OPACITY
);
}
if (isset($_POST['kde']) && $_POST['kde'] == 'levo') {
//ALIGN BOTTOM, LEFT
imagecopymerge(
$source_gd_image,
$overlay_gd_image,
0,
$source_height - $overlay_height,
0,
0,
$overlay_width,
$overlay_height,
WATERMARK_OVERLAY_OPACITY
);
}
imagejpeg($source_gd_image, $output_file_path, WATERMARK_OUTPUT_QUALITY);
imagedestroy($source_gd_image);
imagedestroy($overlay_gd_image);
imagedestroy($overlay_gd_image_resized);
}
/*
* Uploaded file processing function
*/
define('UPLOADED_IMAGE_DESTINATION', 'originals/');
define('PROCESSED_IMAGE_DESTINATION', 'images/');
function process_image_upload($Field)
{
$temp_file_path = $_FILES[$Field]['tmp_name'];
/*$temp_file_name = $_FILES[$Field]['name'];*/
$temp_file_name = md5(uniqid(rand(), true)) . '.jpg';
list(, , $temp_type) = getimagesize($temp_file_path);
if ($temp_type === NULL) {
return false;
}
switch ($temp_type) {
case IMAGETYPE_GIF:
break;
case IMAGETYPE_JPEG:
break;
case IMAGETYPE_PNG:
break;
default:
return false;
}
$uploaded_file_path = UPLOADED_IMAGE_DESTINATION . $temp_file_name;
$processed_file_path = PROCESSED_IMAGE_DESTINATION . preg_replace('/\\.[^\\.]+$/', '.jpg', $temp_file_name);
move_uploaded_file($temp_file_path, $uploaded_file_path);
$result = create_watermark($uploaded_file_path, $processed_file_path);
if ($result === false) {
return false;
} else {
return array($uploaded_file_path, $processed_file_path);
}
}
$result = process_image_upload('File1');
if ($result === false) {
echo '<br>An error occurred during file processing.';
} else {
/*echo '<br>Original image saved as ' . $result[0] . '';*/
echo '<br>Odkaz na obrazek je zde';
echo '<br><img src="' . $result[1] . '" width="500px">';
echo '<br><div class="fb-share-button" data-href="' . $result[1] . '" data-type="button"></div>';
}

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

How to crop this image?

I have this image,
I want to crop this image to several sizes, for that i use this function-
function thumbanail_for_image($Id, $newfilename, $size=NULL) {
$file_extension = substr($newfilename, strrpos($newfilename, '.') + 1);
$arr = explode('.', $newfilename);
$thumb1 = LOCAL_FOLDER . $arr[0] . "_" . $Id . "." . $file_extension;
$thumb2 = LOCAL_FOLDER . $arr[0] . "_" . $Id . "b" . "." . $file_extension;
$old = LOCAL_FOLDER . $newfilename;
$newfilename = LOCAL_FOLDER . $newfilename;
$srcImage = "";
$sizee = getimagesize($newfilename);
switch ($sizee['mime']) {
case "image/jpeg" :
$srcImage = imagecreatefromjpeg($old);
break;
case "image/png":
$srcImage = imagecreatefrompng($old);
break;
case "image/gif":
$srcImage = imagecreatefromgif($old);
break;
}
$srcwidth = $sizee[0];
$srcheight = $sizee[1];
if ($srcwidth > $srcheight || $srcwidth < $srcheight) {
$destwidth1 = 65;
$rat = $destwidth1 / $srcwidth;
$destheight1 = (int) ($srcheight * $rat);
}
elseif ($srcwidth == $srcheight) {
$destwidth1 = 65;
$destheight1 = 65;
}
if ($srcwidth > $srcheight || $srcwidth < $srcheight) {
$destwidth2 = 300;
$rat = $destwidth2 / $srcwidth;
$destheight2 = (int) ($srcheight * $rat);
}
elseif ($srcwidth == $srcheight) {
$destwidth2 = 300;
$destheight2 = 300;
}
$destImage1 = imagecreatetruecolor($destwidth1, $destheight1);
$destImage2 = imagecreatetruecolor($destwidth2, $destheight2);
imagecopyresampled($destImage1, $srcImage, 0, 0, 0, 0, $destwidth1, $destheight1, $srcwidth, $srcheight);
imagecopyresampled($destImage2, $srcImage, 0, 0, 0, 0, $destwidth2, $destheight2, $srcwidth, $srcheight);
if ($sizee['mime'] == "image/jpeg") {
imagejpeg($destImage1, $thumb1, 80);
imagejpeg($destImage2, $thumb2, 80);
} elseif ($sizee['mime'] == "image/png") {
imagepng($destImage1, $thumb1, 80);
imagepng($destImage2, $thumb2, 80);
} elseif ($sizee['mime'] == "image/gif") {
imagegif($destImage1, $thumb1, 80);
imagegif($destImage2, $thumb2, 80);
}
imagedestroy($destImage1);
imagedestroy($destImage2);
chmod($destImage1, 0777);
chmod($destImage2, 0777);
return $destImage1;
}
LOCAL_FOLDER is variable path to local
The problem i saw is when i print $_FILES info about it shows
[type] =>image/jpeg
and when i print getimagesize() function it prints
[mime] => image/png
Please help,
thanks
Why do you not use a lib that handles all these things for you?
For instance, check out WideImage:
include "path-to/WideImage.php";
$image = WideImage::load("path-to/image.jpg");
$cropped = $image->crop(0, 0, 100, 50);
$cropped->saveToFile("cropped-image.jpg");
PHP's POST method uploads page says:
$_FILES['userfile']['type']
The mime type of the file, if the browser provided this information.
An example would be "image/gif". This mime type is however not checked
on the PHP side and therefore don't take its value for granted.
So the image type data here is provided by the client that uploaded the file, and PHP recommends don't trust it. Trust what getimagesize() gives you instead.

Categories