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.
Related
I'm getting my image from base64, decode it, then check if the image width is less than the height. If it is, rotate the image. However, imagerotate() only accepts resource.
imagerotate() expects parameter 1 to be resource, string given
Here is the code:
$file_data = base64decode($input);
list($width, $height) = getimagesizefromstring($file_data);
if($width < $height) {
$file_data = imagerotate($file_data, 90, 0);
}
How do I rotate the image without saving it first?
I ended up properly creating the image resource, this works perfectly:
$file_data = base64decode($input);
list($width, $height) = getimagesizefromstring($file_data);
if($width < $height) {
$file_rotate = imagecreatefromstring($file_data);
$file_rotated = imagerotate($file_rotate, 90, 0);
ob_start();
imagejpeg($file_rotated);
$file_data = ob_get_contents();
ob_end_clean();
}
I have a php code to get an image and resize it. Can't get the output as expected.. Please help me figure out what the exact problem is..!!
<?php
$picture_source = 'image.png';
if ($picture_source != null){
$img1=file_get_contents($picture_source);
$new_img1 = resizeImage($img1, 200, 200);
file_put_contents("i1.png", $new_img1);
}
function resizeImage($img,$newwidth,$newheight) {
list($width, $height) = getimagesizefromstring($img);
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($thumb, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $thumb;
}
You've got some confusion with your variable names and types. You're trying to deal with a filename, the file contents, and an image resource at the same time, and you're using the wrong ones for a few of the functions.
imagecopyresampled takes two image resources (source and destination), but you're passing it the file contents in place of the source.
file_put_contents takes a string for the file contents, but you're passing it the resized image resource.
PHP has native functions for reading the image dimensions and creating an image resource from a filename, so you shouldn't need to ever have the source file contents available as a string.
If you change a few of the variable names and function calls around, you end up with:
<?php
$sourceFilename = 'image.png';
if ($sourceFilename != null){
$newImg = resizeImage($sourceFilename, 200, 200);
imagepng($newImg, "i1.png");
}
function resizeImage($imgFilename, $newWidth, $newHeight) {
list($width, $height) = getimagesize($imgFilename);
$img = imagecreatefrompng($imgFilename);
$thumb = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($thumb, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
return $thumb;
}
Also, you should turn on PHP notices and warnings in your development environment - they will have been trying to help you.
I have used imagecreatefromjpeg("1.jpg") it is showing
Warning: imagecopy() expects parameter 1 to be resource, string given in E:\wamp\www
I am not understanding why it is not working and it tacks as a string, though it is a existing image name on the same file.
$new_image = "assets/small/i/m/".imagecreatetruecolor($size_width, $size_height);
$file = "upl_13541718681354171868The-best-top-desktop-dolphin-wallpapers-hd-dolphins-wallpaper-3.jpg";
$image = imagecreatefromjpeg($file);
imagecopy($new_image, $image, 0, 0, 0, 0, $size_width, $size_height);
imagejpeg($imageOutput, $outputPath, 100);
imagecreatefromjpeg
Returns an image resource identifier on success, FALSE on errors.
so you are probably passing false to
imagecopy
edit
sorry, parameter 1 is the destination. your're passing a string instead of a resource:
From docs:
// Create image instances
$src = imagecreatefromgif('php.gif');
$dest = imagecreatetruecolor(80, 40);
// Copy
imagecopy($dest, $src, 0, 0, 20, 13, 80, 40);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Save image from one format to another with php gd2
I am converting any image format to JPEG or JPG. Code for converting image to jpg is
function converttojpg($originalimg)
{
$filetype = #end(explode(".", $originalimg));
echo $originalimg . " asdasdfs";
if (strtolower($filetype) == 'jpg' or strtolower($filetype) == 'jpeg')
{
$srcImg = imagecreatefromjpeg($originalimg);
imagejpeg($srcImg,$originalimg,100);
imagedestroy($srcImg);
}
if (strtolower($filetype) == 'png')
{
$srcImg = imagecreatefrompng($originalimg);
imagejpeg($srcImg,$originalimg,100);
imagedestroy($srcImg);
}
if (strtolower($filetype) == 'gif')
{
echo "executed";
$srcImg = imagecreatefromgif($originalimg);
imagejpeg($srcImg,$originalimg,100);
imagedestroy($srcImg);
}
}
After that i resize that converted image, whose code is
function resizeImage($originalImage,$toWidth,$toHeight)
{
// Get the original geometry and calculate scales
list($width, $height) = getimagesize($originalImage);
$xscale=$width/$toWidth;
$yscale=$height/$toHeight;
// Recalculate new size with default ratio
if ($yscale>$xscale)
{
$new_width = round($width * (1/$yscale));
$new_height = round($height * (1/$yscale));
}
else
{
$new_width = round($width * (1/$xscale));
$new_height = round($height * (1/$xscale));
}
// Resize the original image
$imageResized = imagecreatetruecolor($new_width, $new_height);
$imageTmp = imagecreatefromjpeg ($originalImage);
imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
return $imageResized;
}
and on Every image it reports errors and warning which are
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg, libjpeg: recoverable error: Corrupt JPEG data: 9 extraneous bytes before marker 0xd9 in E:\xampp\htdocs\photo\functions.php on line 33
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: 'userphotos/corrupted_image_1.jpg' is not a valid JPEG file in E:\xampp\htdocs\photo\functions.php on line 33
Warning: imagejpeg() expects parameter 1 to be resource, boolean given in E:\xampp\htdocs\photo\functions.php on line 34
Warning: imagedestroy() expects parameter 1 to be resource, boolean given in E:\xampp\htdocs\photo\functions.php on line 35
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg, libjpeg: recoverable error: Corrupt JPEG data: 9 extraneous bytes before marker 0xd9 in E:\xampp\htdocs\photo\functions.php on line 22
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: 'userphotos/53.jpg' is not a valid JPEG file in E:\xampp\htdocs\photo\functions.php on line 22
Warning: imagecopyresampled() expects parameter 2 to be resource, boolean given in E:\xampp\htdocs\photo\functions.php on line 23
userphotos/MG_diesel-04.gif_thumb.png asdasdfsuserphotos/Porsche_911_996_Carrera_4S.jpg asdasdfs
Please help me in solving that problem. I have to complete it.
Don't use extension to determine file type. To check if given file is an image and in format that allows GD to manipulate it, use getimagesize
<?php
$image = #imagecreatefromstring(file_get_contents($file_path));
if ($image === false) {
throw new Exception (sprintf('invalid image or file not found, file=%s', $file_path));
}
?>
imagecreatefromstring detects image type and creates an image resource, otherwise exception is thrown.
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