How to crop this image? - php

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.

Related

How to split "non-animated and animated" pictures, for correctly use resize function

With this script I can upload multiple images with animations or without.
Included many functions: resize, watermark, correct orientation, send data to ajax, etc...
<?php
define('FORUM_PATH', '/.../');
require_once (FORUM_PATH . '.../login.php');
$ipbMemberLoginApi = new apiMemberLogin();
$ipbMemberLoginApi->init();
$member = $ipbMemberLoginApi->getMember();
$id = ($member['member_id']);
$countFiles = count($_FILES['files']['name']);
$upload_location = "uploads/$id/" . date("ymd") . "/";
if (!is_dir($upload_location)) mkdir($upload_location, 0755, true);
$chars = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789';
$files_arr = array();
for ($i = 0;$i < $countFiles;$i++) {
$fileName = $_FILES['files']['name'][$i];
$ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
$valid_ext = array("png", "jpeg", "jpg", "webp", "gif", "bmp");
if (in_array($ext, $valid_ext)) {
$imgName = $chars[mt_rand(1, 62) ] . substr(str_shuffle(uniqid()), 0, 6) . '.' . $ext;
$path = $upload_location . $imgName;
if (move_uploaded_file($_FILES['files']['tmp_name'][$i], $path)) {
$abort = false;
$im = new Imagick();
try {
$im->pingImage($path);
}
catch(ImagickException $e) {
unlink($path);
$files_arr['BadIMG'][] = $fileName;
$abort = true;
}
if (!$abort) {
if ($ext == "gif") {
$file = file_get_contents($path);
$animated = preg_match('#(\x00\x21\xF9\x04.{4}\x00\x2C.*){2,}#s', $file);
}
if ($animated != 1) {
//For non-animated pictures
$image = new Imagick($path);
$props = $image->getImageProperties('exif:Orientation', true);
$orientation = isset($props['exif:Orientation']) ? $props['exif:Orientation'] : null;
if ($orientation != 0) {
switch ($image->getImageOrientation()) {
case Imagick::ORIENTATION_TOPLEFT:
break;
case Imagick::ORIENTATION_TOPRIGHT:
$image->flopImage();
break;
case Imagick::ORIENTATION_BOTTOMRIGHT:
$image->rotateImage("#000", 180);
break;
case Imagick::ORIENTATION_BOTTOMLEFT:
$image->flopImage();
$image->rotateImage("#000", 180);
break;
case Imagick::ORIENTATION_LEFTTOP:
$image->flopImage();
$image->rotateImage("#000", -90);
break;
case Imagick::ORIENTATION_RIGHTTOP:
$image->rotateImage("#000", 90);
break;
case Imagick::ORIENTATION_RIGHTBOTTOM:
$image->flopImage();
$image->rotateImage("#000", 90);
break;
case Imagick::ORIENTATION_LEFTBOTTOM:
$image->rotateImage("#000", -90);
break;
default:
break;
}
$image->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
$image->writeImage($path);
}
$im->readImage($path);
$max_width = 1024;
$max_height = 768;
$im->stripImage();
$im->resizeImage(min($im->getImageWidth(), $max_width), min($im->getImageHeight(), $max_height), imagick::FILTER_CATROM, 1, true);
$imWidth = $im->getImageWidth();
$imHeight = $im->getImageHeight();
if ($imWidth < 150 || $imHeight < 150) {
$watermark = new Imagick("noWatermark.png");
} elseif ($imWidth < 401 || $imHeight < 401) {
$watermark = new Imagick("watermark_small.png");
} else {
$watermark = new Imagick("watermark.png");
}
$margin_right = 2;
$margin_bottom = 2;
$x = $im->getImageWidth() - $watermark->getImageWidth() - $margin_right;
$y = $im->getImageHeight() - $watermark->getImageHeight() - $margin_bottom;
$im->compositeImage($watermark, Imagick::COMPOSITE_OVER, $x, $y);
$watermark->destroy();
file_put_contents($path, $im);
$files_arr['GoodIMG'][] = str_replace('uploads/', '', $path);
} else {
//For animated pictures
system("convert $path -coalesce -repage 0x0 -scale 800x\> -layers Optimize $path");
$imGif = new Imagick($path);
$max_size = 180;
$imGifWidth = $imGif->getImageWidth();
$imGifHeight = $imGif->getImageHeight();
if ($imGifWidth || $imGifHeight > 180) {
system("convert $path -coalesce null: watermark.png -gravity SouthEast -geometry +0+0 -layers composite -layers optimize $path");
}
$files_arr['GoodIMG'][] = str_replace('uploads/', '', $path);
}
}
}
}
}
header('Content-Type: application/json');
echo json_encode($files_arr);
die;
PHP Version 5.6.40
But have problem:
If I upload ($animated == 1).GIF together with ($animated != 1), this picture ($animated != 1) goes in function for resize animated pictures.
How to split animated picture from non-animated picture correctly if I upload together?
Added more details:
If try upload:
AAA.gif - animated
BBB.jpeg - non-animated
BBB.jpeg goes in function for resize animated pictures.
But, if try upload:
AAA.jpeg - non-animated
BBB.gif - animated
AAA.jpeg goes in function for resize non-animated pictures. This is a correct.
Solved
if ($ext == "gif") {
$file = file_get_contents($path);
$animated = preg_match('#(\x00\x21\xF9\x04.{4}\x00\x2C.*){2,}#s', $file);
} else {
$animated = 0;
}
After you find an animated image and set $animated to 1, you only set $animated back to 0, when you find a non-animated gif image, but not if you find a non-animated non-gif image.

Opencart - Image Resize

i am using opencart 2.1.x version of opencart and i am facing an issue with images in displaying the images.
But image resize function adding Noise in background. It can be seen as in below image::
Tilt the laptop screen or desktop scree to observe noise
Function to resize the image is:
catalog/model/tool/image.php
public function resize($filename, $width, $height) {
if (!is_file(DIR_IMAGE . $filename)) {
return;
}
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$old_image = $filename;
$new_image = 'cache/' . utf8_substr($filename, 0,
utf8_strrpos($filename, '.')) . '-' . $width . 'x' . $height . '.'.$extension;
list($width_orig, $height_orig) = getimagesize(DIR_IMAGE . $old_image);
if ($width_orig != $width || $height_orig != $height) {
$image = new Image(DIR_IMAGE . $old_image);
$image->resize($width, $height);
$image->save(DIR_IMAGE . $new_image);
} else {
copy(DIR_IMAGE . $old_image, DIR_IMAGE . $new_image);
}
system/library/image.php
public function resize($width = 0, $height = 0, $default = '') {
if (!$this->width || !$this->height) {
return;
}
$xpos = 0;
$ypos = 0;
$scale = 1;
$scale_w = $width / $this->width;
$scale_h = $height / $this->height;
if ($default == 'w') {
$scale = $scale_w;
} elseif ($default == 'h') {
$scale = $scale_h;
} else {
$scale = min($scale_w, $scale_h);
}
if ($scale == 1 && $scale_h == $scale_w && $this->mime != 'image/png') {
return;
}
$new_width = (int)($this->width * $scale);
$new_height = (int)($this->height * $scale);
$xpos = (int)(($width - $new_width) / 2);
$ypos = (int)(($height - $new_height) / 2);
$image_old = $this->image;
$this->image = imagecreatetruecolor($width, $height);
if ($this->mime == 'image/png') {
imagealphablending($this->image, false);
imagesavealpha($this->image, true);
$background = imagecolorallocatealpha($this->image, 255, 255, 255, 127);
imagecolortransparent($this->image, $background);
} else {
$background = imagecolorallocate($this->image, 255, 255, 255);
}
imagefilledrectangle($this->image, 0, 0, $width, $height, $background);
imagecopyresampled($this->image, $image_old, $xpos, $ypos, 0, 0, $new_width,
$new_height, $this->width, $this->height);
imagedestroy($image_old);
$this->width = $width;
$this->height = $height;
}
Please assist i ngetting rid from background noise.
It looks like your catalog/model/tool/image.php code snippet is incomplete.
I solved this issue by commenting main part of a function code and returning the path to initial image (OpenCart 2.3.0.2):
<?php
class ModelToolImage extends Model {
public function resize($filename, $width, $height) {
if (!is_file(DIR_IMAGE . $filename) || substr(str_replace('\\', '/', realpath(DIR_IMAGE . $filename)), 0, strlen(DIR_IMAGE)) != DIR_IMAGE) {
return;
}
/*$extension = pathinfo($filename, PATHINFO_EXTENSION);
$image_old = $filename;
$image_new = 'cache/' . utf8_substr($filename, 0, utf8_strrpos($filename, '.')) . '-' . (int)$width . 'x' . (int)$height . '.' . $extension;
if (!is_file(DIR_IMAGE . $image_new) || (filectime(DIR_IMAGE . $image_old) > filectime(DIR_IMAGE . $image_new))) {
list($width_orig, $height_orig, $image_type) = getimagesize(DIR_IMAGE . $image_old);
if (!in_array($image_type, array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF))) {
return DIR_IMAGE . $image_old;
}
$path = '';
$directories = explode('/', dirname($image_new));
foreach ($directories as $directory) {
$path = $path . '/' . $directory;
if (!is_dir(DIR_IMAGE . $path)) {
#mkdir(DIR_IMAGE . $path, 0777);
}
}
if ($width_orig != $width || $height_orig != $height) {
$image = new Image(DIR_IMAGE . $image_old);
$image->resize($width, $height);
$image->save(DIR_IMAGE . $image_new);
} else {
copy(DIR_IMAGE . $image_old, DIR_IMAGE . $image_new);
}
}
$image_new = str_replace(' ', '%20', $image_new); // fix bug when attach image on email (gmail.com). it is automatic changing space " " to +
if ($this->request->server['HTTPS']) {
return $this->config->get('config_ssl') . 'image/' . $image_new;
} else {
return $this->config->get('config_url') . 'image/' . $image_new;
}*/
return 'image/' . $filename;
}
}
Have You tried by changing quality to 100 on function save in parameter
public function save($file, $quality = 100) {
$info = pathinfo($file);
$extension = strtolower($info['extension']);
if (is_resource($this->image)) {
if ($extension == 'jpeg' || $extension == 'jpg') {
imagejpeg($this->image, $file, $quality);
} elseif ($extension == 'png') {
imagepng($this->image, $file);
} elseif ($extension == 'gif') {
imagegif($this->image, $file);
}
imagedestroy($this->image);
}
}

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);

Php code to create thumb not working after update

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.

Insert Into database upon image upload?

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

Categories