Generate Thumbnail from base64_decode from mySQL - php

Im trying to make code for generate thumbnail from base64_decode from mySQL Database but problem is why it said file is not valid JPEG im sure that source file is pure JPG file format. then I can't solve :(
source file (BASE64_ENCODE):
http://pastebin.com/wFBcd79B
image.php in view/Helper folder code:
<?php
class ImageHelper extends Helper {
var $helpers = array('Html');
var $cacheDir = 'imagecache';
function getfile($i) {
preg_match_all("/data:(.*);base64,/", $i, $temp_imagetype);
$imagetype = $temp_imagetype[1][0];
$image = base64_decode(preg_replace("/data.*base64,/","",$i));
//echo $image;
ob_start();
//header("Content-type: ".$imagetype);
header('Content-Type: image/jpeg');
print($image);
$data = ob_get_clean();
//file_put_contents($this->webroot.'tmp/temp.jpg', 'test' );
file_put_contents(ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.'tmp/temp.jpg', $data );
//return ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.'tmp/temp2.jpg';
//return 'temp2.jpg';
return 'temp.jpg';
//}
}
//source from: http://bakery.cakephp.org/articles/hundleyj/2007/02/16/image-resize-helper and modified for base64_decode
function resize($path, $width, $height, $aspect = true, $htmlAttributes = array(), $return = false) {
$types = array(1 => "gif", "jpeg", "png", "swf", "psd", "wbmp"); // used to determine image type
//$fullpath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.$this->themeWeb.IMAGES_URL;
$fullpath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.IMAGES_URL;
$temppath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.'tmp/';
//$formImage = imagecreatefromstring(base64_decode(preg_replace("/data.*base64,/","",$path)));
//$url = $formImage;
//$path = $this->getfile($path);
$url = $temppath.$path;
//$url = preg_replace("/data.*base64,/","",$path);
//$url = base64_decode($url);
if (!($size = getimagesize($url)))
return; // image doesn't exist
if ($aspect) { // adjust to aspect.
if (($size[1]/$height) > ($size[0]/$width)) // $size[0]:width, [1]:height, [2]:type
$width = ceil(($size[0]/$size[1]) * $height);
else
$height = ceil($width / ($size[0]/$size[1]));
}
$relfile = $this->cacheDir.'/'.$width.'x'.$height.'_'.basename($path); // relative file
$cachefile = $fullpath.$this->cacheDir.DS.$width.'x'.$height.'_'.basename($path); // location on server
if (file_exists($cachefile)) {
$csize = getimagesize($cachefile);
$cached = ($csize[0] == $width && $csize[1] == $height); // image is cached
if (#filemtime($cachefile) < #filemtime($url)) // check if up to date
$cached = false;
} else {
$cached = false;
}
if (!$cached) {
$resize = ($size[0] > $width || $size[1] > $height) || ($size[0] < $width || $size[1] < $height);
} else {
$resize = false;
}
if ($resize) {
$image = call_user_func('imagecreatefrom'.$types[$size[2]], $url);
if (function_exists("imagecreatetruecolor") && ($temp = imagecreatetruecolor ($width, $height))) {
imagecopyresampled ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
} else {
$temp = imagecreate ($width, $height);
imagecopyresized ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
}
call_user_func("image".$types[$size[2]], $temp, $cachefile);
imagedestroy ($image);
imagedestroy ($temp);
}
return $this->output(sprintf($this->Html->image($relfile,$htmlAttributes)));
}
}
?>
'index.php' in view folder code:
<?php
foreach ($products as $product):
echo $this->Image->resize($this->Image->getfile($product['Product']['image1']), 120, 120, false);
endforeach;
?>
Output is error log:
> Warning (2): imagecreatefromjpeg() [function.imagecreatefromjpeg]:
> gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file
> [APP/View/Helper/image.php, line 86]
> Warning (2): imagecreatefromjpeg() [function.imagecreatefromjpeg]:
> '/Users/user/Sites/mycakeapp/app/webroot/tmp/temp.jpg' is not a valid
> JPEG file [APP/View/Helper/image.php, line 86]
> Warning (2): imagecopyresampled() expects parameter 2 to be resource, boolean given
> [APP/View/Helper/image.php, line 88]
> Warning (2): imagedestroy() expects parameter 1 to be resource, boolean given
> [APP/View/Helper/image.php, line 94]

The base64 encoded data you link to is exactly 2¹⁶ (65536) bytes long. That number is just too round to be a coincidence.
Is the database column defined as TEXT? Convert it to something bigger, like MEDIUMTEXT or LONGTEXT.
It would make more sense to store images in the file system. While databases can store arbitrary data like files, there are limitations that make it impractical: A larger amount of data has to be transferred from the database server to the application over a network so there's a performance issue. Huge databases take longer to back up. And you may need to modify database settings:
The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers. You can change the message buffer size by changing the value of the max_allowed_packet variable, but you must do so for both the server and your client program.
http://dev.mysql.com/doc/refman/5.0/en/blob.html

Related

How to adjust this script to use Glob instead of 1 file

I have created this script based on reading other posts on StackOverflow. The script creates a thumbnail from the original image and adds it to a folder. The source images are located on my local server so Glob would work however I am not sure how to adjust this script so that it will run this function on all files in a folder (Glob). I realize it may be memory intensive but I only need to do it a few times on several folders and I'll be done with it.
Just in case you are questioning the reason I have included $height2, it is a little hack I came up with where we create the thumbnail while maintaining the aspect ratio then only save the top 250px so that the thumb is 250 x 250 but not distorted (stretched). It works great.
I just need to adjust to do a batch of all images in the source folder.
Any help would be great. Please keep in mind that I am a front end developer (html and css) and not great at PHP. This script alone took me forever to make work lol.
If anyone can help me adjust it for a full folder, that would be great.
foreach(glob('SourceFolder/*.jpg', GLOB_NOSORT) as $url); {
Thumbnail ($url, "DestinationFolder/*.jpg");
function Thumbnail($url, $filename, $width = 250, $height = true, $height2 = 250) {
// download and create gd image
$image = ImageCreateFromString(file_get_contents($url));
// calculate resized ratio
// Note: if $height is set to TRUE then we automatically calculate the height based on the ratio
$height = $height === true ? (ImageSY($image) * $width / ImageSX($image)) : $height;
// create image
$output = ImageCreateTrueColor($width, $height2);
ImageCopyResampled($output, $image, 0, 0, 0, 0, $width, $height, ImageSX($image), ImageSY($image));
// save image
ImageJPEG($output, $filename, 100);
}
}
I was able to adjust the code on my own after reading the online PHP manual.
The final code:
foreach (glob("SourceFolder/*.jpg") as $url) {
$destdir = "Destination/" . basename($url, null);
$width = 250;
$height = true;
// download and create gd image
$image = ImageCreateFromString(file_get_contents($url));
// calculate resized ratio
// Note: if $height is set to TRUE then we automatically calculate the height based on the ratio
$height = $height === true ? (ImageSY($image) * $width / ImageSX($image)) : $height;
// create image
$output = ImageCreateTrueColor($width, $height);
ImageCopyResampled($output, $image, 0, 0, 0, 0, $width, $height, ImageSX($image), ImageSY($image));
// save image
ImageJPEG($output, $destdir, 100);
}
This solution uses opendir and readdir. I have found that this approach can
handle folders with more files.
// Set desired height and width
$desiredWidth = 250;
$desiredHeight = true;
// Set source and destination folders
$srcFolder = "SourceFolder";
$destFolder = "Destination";
// This is more memory efficient than using glob()
$dh = opendir($srcFolder);
if ( ! $dh ) {
die('Unable to open folder ' . $srcFolder);
}
while($filename = readdir($dh) ) {
// only process jpg files.
if ( preg_match('/.jpg$/', $filename) ) {
$inputFile = sprintf('%s/%s', $srcFolder, $filename);
$outputFile = sprintf('%s/%s', $destFolder, $filename);
echo "file: $filename\n";
echo "input: $inputFile\n";
echo "output: $outputFile\n";
$inputImage = #ImageCreateFromJpeg($inputFile);
if ( $inputImage ) {
// calculate resized ratio
// Note: if $height is set to TRUE then we automatically calculate the height based on the ratio
$height = $desiredHeight === true ? (ImageSY($inputImage) * $desiredWidth / ImageSX($inputImage)) : $desiredHeight;
// create image
$outputImage = ImageCreateTrueColor($desiredWidth, $height);
ImageCopyResampled($outputImage, $inputImage, 0, 0, 0, 0, $desiredWidth, $height, ImageSX($inputImage), ImageSY($inputImage));
// save image
ImageJPEG($outputImage, $outputFile, 100);
ImageDestroy($inputImage);
ImageDestroy($outputImage);
} else {
echo "Could not process file\n";
}
}
}
closedir($dh);

PHP resize image & store in BLOB & access though base64_encode

On image upload , I want to resize image to 400 X 400 ratio. I have used GD library code as :
$profilePicture = $_FILES['imgProfilePicture']['tmp_name'];
// Get new dimensions
list($width_orig, $height_orig, $type) = getimagesize($profilePicture);
$ratio_orig = $width_orig/$height_orig;
if ($intWidth/$intHeigth > $ratio_orig) {
$intWidth = $intHeigth*$ratio_orig;
} else {
$intHeigth = $intWidth/$ratio_orig;
}
// Resample
$thumb = imagecreate($intWidth, $intHeigth);
ob_start();
$extension = image_type_to_extension($type);
if($extension == ".jpg" OR $extension=='.jpeg'){
$source = ImageCreateFromJpeg($profilePicture);
$newImage = imagejpeg($thumb, null, 9);
}elseif ($extension == ".gif"){
$source = ImageCreateFromGIF($profilePicture);
$newImage = imagegif($thumb, null, 9);
}elseif ($extension == '.png'){
$source = imageCreateFromPNG($profilePicture);
$newImage = imagepng($thumb, null, 9);
}
imagecopyresized($thumb, $source, 0, 0, 0, 0, $intWidth, $intHeigth, $width_orig, $height_orig);
$stream = ob_get_clean();
$imgProfilePicture = file_get_contents($stream);
$sql="update `".$doctorTableName."` set`imgProfilePicture`='".$imgProfilePicture."' where id='".$id."'";
$wpdb->query($sql);
& I have shown image using this code :
<img width="70" height="70" src="data:image/jpeg;base64, '.base64_encode($doctor->imgProfilePicture).' "/>
But I am getting error as :
Warning: file_get_contents() expects parameter 1 to be a valid path, string given
I got a code for this on this link under user contributions scaleImageFileToBlob()
http://php.net/manual/en/function.imagejpeg.php

How to resize image using Gd library ? PHP

after receiving the image from the client , I would like to resize it and then store it .
I am using this function:
function PIPHP_ImageResize($image, $w, $h)
{
$oldw = imagesx($image);
$oldh = imagesy($image);
$temp = imagecreatetruecolor($w, $h);
imagecopyresampled($temp, $image, 0, 0, 0, 0,
$w, $h, $oldw, $oldh);
return $temp;
}
$image = PIPHP_ImageResize($_FILES['file']['tmp_name'],10,10);
move_uploaded_file($image, $newname);
unfortunately I got these warning:
Warning: imagesx() expects parameter 1 to be resource, string given...
Warning: imagesy() expects parameter 1 to be resource, string given ...
Warning: imagecopyresampled() expects parameter 2 to be resource, string given ...
Warning: move_uploaded_file() expects parameter 1 to be string, resource given ...
How could I fix the problem !!
imagesx expect an image resource as first parameter. You have to create one using the appropriate function, imagecreatefromjpeg or imagecreatefrompng for example.
function PIPHP_ImageResize($image, $w, $h)
{
$oldw = imagesx($image);
$oldh = imagesy($image);
$temp = imagecreatetruecolor($w, $h);
imagecopyresampled($temp, $image, 0, 0, 0, 0, $w, $h, $oldw, $oldh);
return $temp;
}
if (move_uploaded_file($_FILES['file']['tmp_name'], $newname)) {
$uploadedImage = imagecreatefromjpeg($newname);
if (!$uploadedImage) {
throw new Exception('The uploaded file is corrupted (or wrong format)');
} else {
$resizedImage = PIPHP_ImageResize($uploadedImage,10,10);
// save your image on disk
if (!imagejpeg ($resizedImage, "new/filename/path")) {
throw new Exception('failed to save resized image');
}
}
} else {
throw new Exception('failed Upload');
}
I've added a minimal and insufficient error handling, you should check, for example, the format of the uploaded file and use the appropriate image creator function, or check if the uploaded file is an image.
Addendum
You can determine the type of the presumed uploaded image using getimagesize function.
getimagesize return an array. If the image type is supported the array[2] value return the type of the image. if the file is not an image, or its format is not supported, the array[0] value is zero. Once you know the file format of the image you can use one of the imagecreatefromxxx functions to create the appropriate image.

Does the $_FILES array get deleted after it's used in a function?

I am resizing an image from a user upload form, and I have passed the contents of the $_FILES array to my resizing function. The function uses GD to resize the image and save it in the desired directory.
I need to make two copies of the image: a large copy and a small copy for a thumbnail. The problem arises when I try to call the function for a second time (but with different dimensions) to make the thumbnail image. I get an unidentified index array message for the $_FILES array.
Is the $_FILES array being deleted automatically after passing it to the function, despite the fact that I have not used the functions to clear it?
FUNCION CALL is as follows
if ($_FILES['image']['error'] != 4){
foto($_FILES['image'], $THUMBS_DIR, 400, 400, 1);
foto($_FILES['image'], $THUMBS_DIR, 70, 70, 1);
}
FUNCTION
/*foto function, foto upload, where to save, fotowidth, fotosize,*/
function foto($_FILES, $THUMBS_DIR, $MAX_WIDTH, $MAX_HEIGHT){
/*generate random name*/
$fecha = time();$passpart1 = $fecha;$passpart2 = mt_rand(1, 1000);$ps = $passpart1.$passpart2;$ps2= $passpart1.$passpart2.'thumb';$thumbref='0';
if (is_uploaded_file($_FILES['tmp_name']))
{
/*resize ratio*/
$original = $_FILES['tmp_name'];
list($width, $height, $type) = getimagesize($original);
if ($width <= $MAX_WIDTH && $height <= $MAX_HEIGHT) {$ratio = 1;}
elseif ($width > $height) {$ratio = $MAX_WIDTH/$width;}
else {$ratio = $MAX_HEIGHT/$height;}
$imagetypes = array('/\.gif$/','/\.jpg$/','/\.jpeg$/','/\.png$/');
$name = preg_replace($imagetypes, '', basename($original));
$name=$ps;switch($type)
{case 1:$source = # imagecreatefromgif($original);if (!$source) {$result = 'Cannot process GIF files. Please use JPEG or PNG.';}break;
case 2:$source = imagecreatefromjpeg($original);break;
case 3:$source = imagecreatefrompng($original);break;
default:$source = NULL;$result = 'Cannot identify file type.';}
if (!$source) {$result = 'Problem copying original';}
else {
$thumb_width = round($width * $ratio);
$thumb_height = round($height * $ratio);
$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height);
switch($type)
{case 1:if (function_exists('imagegif')) {$success = imagegif($thumb, $THUMBS_DIR.$ps.'.gif');$thumb_name = $ps.'.gif';}
else {$success = imagejpeg($thumb, $THUMBS_DIR.$ps.'.jpg', 50);$thumb_name = $ps.'.jpg';}break;
case 2:$success = imagejpeg($thumb, $THUMBS_DIR.$ps.'.jpg', 100);$thumb_name = $ps.'.jpg';break;
case 3:$success = imagepng($thumb, $THUMBS_DIR.$ps.'.png');$thumb_name = $ps.'.png';}
/*destroy temp or not*/
if ($success) {$result = "$thumb_name created";}
}
$fotref = $thumb_name;
}
else{$errorreport='error with upload';}}
Hello again i have posted the code, I didnt originally post it becuase i didnt expect people to want to see it , I really appreciate it, Thanks to everybody.
I'm pretty sure this is because $_FILES is a superglobal, and thus when you use it as the argument name in your function foto, it gets clobbered, such that $_FILES becomes whatever you passed as the first argument.
Rewrite the foto function with a variable besides $_FILES, e.g.:
function foto($image, $THUMBS_DIR, $MAX_WIDTH, $MAX_HEIGHT){
// rest of code here with $_FILES changed to $image
}
Alternatively, as $_FILES is a super global, you could skip using it as a parameter at all, changing the call to be:
foto($THUMBS_DIR, 400, 400, 1)
And the function to be of the form:
function foto($THUMBS_DIR, $MAX_WIDTH, $MAX_HEIGHT){
//code placeholder
if (is_uploaded_file($_FILES['image']['tmp_name'])) {
$original = $_FILES['image']['tmp_name'];
//rest of code
}

getimagesize - failed to open stream: Connection timed out in

In my php script in am trying to get an image from a URL, resize it, and upload it to my server. The script can be seen at http://getsharp.net/imageupload.php?admin=rene - The script is seen below (there is of course also some other PHP and HTML in it, but this is the part giving me an issue):
$admin = $_REQUEST['admin'];
$url = $_POST['uploadlink'];
if ($_POST['filename']){
$filename = $_POST['filename'].".jpg";
} else {
$urlinfo = parse_url($url);
$filename = basename($urlinfo['path']);
$filenamearray = explode(".", $filename);
$filenamebase = $filenamearray[0];
$filenamebase = substr($filenamebase, 0, 20); // max 20 characters
$filename = $filenamebase.".jpg";
}
// Get new dimensions
list($width, $height) = getimagesize($url);
$new_width = 300;
$ratio = $height/$width;
$new_height = 300*$ratio;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
if(exif_imagetype($url) == IMAGETYPE_GIF){
$image = imagecreatefromgif($url);
}else if(exif_imagetype($url) == IMAGETYPE_JPEG){
$image = imagecreatefromjpeg($url);
}else if(exif_imagetype($url) == IMAGETYPE_PNG){
$image = imagecreatefrompng($url);
}else{
$image = false;
}
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
if(is_dir("images/upload/".$admin."/")){
// Output
imagejpeg($image_p, "images/upload/".$admin."/".$filename);
imagedestroy($image_p);
}else{
mkdir("images/upload/".$admin."/");
// Output
imagejpeg($image_p, "images/upload/".$admin."/".$filename);
imagedestroy($image_p);
}
$URL="http://getsharp.net/imageupload.php?admin=".$admin;
header ("Location: $URL");
Everything is working fine, except that when I throw in a new URL it gives me the following error: Warning: getimagesize(http://buffalocomputerconsulting.com/images/computer.jpg): failed to open stream: Connection timed out in.
However, if i throw in the exact same URL right after, there is no problem, and the image is being uploaded. So every time I try a new URL the first time, it gives me the above error. How can this be?
Thanks.
Your DNS resolves too slowly
Your server tries a nonreplying DNS first
Your server tries to connect on IPv6 first
Your uplink is slow as molasses but it has a caching proxy
I am sure there are more. Try your script on another machine and see whether it changes.

Categories