Want to validate image raw data using php - php

I want to validate whether the image raw data is valid or not.
Below is my code :
private function __blobToImage($imagerawdata)
{
$imagedata = base64_decode($imagerawdata);
// Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');
$path = WWW_ROOT . "commapp_images".'/';
$file = mktime().".png";
$filepath = $path.$file;
// Output the image
$image = imagecreatefromstring($imagedata);
ob_start();
imagejpeg($image, $filepath, 80);
ob_get_contents();
ob_end_clean();
return $file;
}
While using my code I'm getting the below error
"Notice (8): imagecreatefromstring() [function.imagecreatefromstring]: gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file"
Any one please help me as because I strucked here with out any solution.

imagecreatefromstring already does that, it returns false on failure. So you could suppress it's message and check for the return value:
$image = #imagecreatefromstring($imagedata);
if ($image !== false)
{
...
}
Edit: You don't need the header and output buffering if you are saving to a file and you are saving a jpeg with the png extension.

Related

An image created by PHP has no extension and is not treated as an image

I am loading an image from a remote server (google for example), but PHP never treats it as an image. This is my code:
$photo = imagecreatefromstring(file_get_contents("https://some.com/image.jpg"));
$filename = $photo["name"];
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); //returns ""
$filepath = $photo["tmp_name"];
is_array(getimagesize($filepath); //returns false
What am I doing wrong?
imagecreatefromstring returns an image not array.
$photo = imagecreatefromstring(file_get_contents("https://some.com/image.jpg"));
ob_end_clean();
header('Content-type: image/jpeg');
imagejpeg($photo, null, 80);
If this code doesn't produce an image then start debugging from finding out the return value of file_get_contents().
Also - after creating an image (using any of imagecreatefrom... functions) you are dealing with image resource, not file system or any other object. Image resource does not have information you are trying to extract (name, pathinfo etc.)

Imagecreatefromwebp(): WebP decode: fail to decode input data

I am trying to convert a webp file to JPEG using imagecreatefromwebp() but unfortunately, it throws me a warning: Warning: imagecreatefromwebp(): WebP decode: fail to decode input data.
Here's my code
$filename = dirname(__FILE__)."\\".$keyword."1.webp"; // $keyword = 'xyz';
$im = imagecreatefromwebp($filename);
// Convert it to a jpeg file with 100% quality
imagejpeg($im, './example.jpeg', 100);
imagedestroy($im);
Please help.
i am using this code, it works fine for me. Here $data contains the base64encoded data
$im = imagecreatefromwebp($data);
$imageResult = imagejpeg($im, $destinationPath . $fileName, 100);
imagedestroy($im);
The imagecreatefromwebp() function accepts either a valid file or URL. You can also pass the your binary data in that function. You can check the function definition and example here http://php.net/manual/en/function.imagecreatefromwebp.php

php imagick - read image from base64

I am manipulating images with js, and I'd like to save these transformed images. I'm posting this data with ajax:
image : canvas.toDataURL('image/jpeg')
This way, I get the base64 code for the image, but I can't find a way to read it with Imagick.
This is my process:
$img = new Imagick();
$decoded = base64_decode($_POST['image']);
$img->readimageblob($decoded);
But this fails:
Fatal error: Uncaught exception 'ImagickException' with message 'no decode delegate for this image format `' # error/blob.c/BlobToImage/360' in /Library/WebServer/Documents/test/save.php:7
Stack trace:
#0 /Library/WebServer/Documents/test/save.php(7): Imagick->readimageblob('u?Z?f?{??z?????...')
Any ideas why?
Figured out.
I had to remove the data:image/png;base64, part from the posted string, and then imagick could interpret it as blob.
readImageBlob — Reads image from a binary string : http://php.net/manual/en/imagick.readimageblob.php
$base64 = "iVBORw0KGgoAAAAN....";
$imageBlob = base64_decode($base64);
$imagick = new Imagick();
$imagick->readImageBlob($imageBlob);
header("Content-Type: image/png");
echo $imagick;
Read this url;--
PHP-Imagemagick image display
or try it:-
$thumbnail = $img->getImageBlob();
$contents = ob_get_contents();
ob_end_clean();
echo "<img src='data:image/jpg;base64,".base64_encode($contents)."' />";

imagecreatefromjpeg() returns a black image when resized

I have following code
// load image and get image size
$img = imagecreatefrompng( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $imageWidth;
$new_height = 500;
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
It works fine with some images..but with certain images it shows an error like
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error:
Warning: imagesx() expects parameter 1 to be resource, boolean given
Warning: imagesy() expects parameter 1 to be resource, boolean given
I have also enabled
gd.jpeg_ignore_warning = 1
in php.ini
Any help appreciated.
According to a blog post from (Feb 2010) its a bug in the implementation of imagecreatefromjpeg which should return false but throws an error instead.
The solution is to check for the filetype of your image (I removed the duplicate call to imagecreatefromjpeg because its totally superfluous; we already check for right file type before and if an error occurs due to some other reason, imagecreatefromjpeg will return false correctly):
function imagecreatefromjpeg_if_correct($file_tempname) {
$file_dimensions = getimagesize($file_tempname);
$file_type = strtolower($file_dimensions['mime']);
if ($file_type == 'image/jpeg' || $file_type == 'image/pjpeg'){
$im = imagecreatefromjpeg($file_tempname);
return $im;
}
return false;
}
Then you can write your code like this:
$img = imagecreatefrompng_if_correct("{$pathToImages}{$fname}");
if ($img == false) {
// report some error
} else {
// enter all your other functions here, because everything is ok
}
Of course you can do the same for png, if you want to open a png file (like your code suggests). Actually, usually you will check which filetype your file really has and then call the correct function between the three (jpeg, png, gif).
Please see PHP Bug #39918 imagecreatefromjpeg doesn't work. The suggestion is to change the GD setting for jpeg image loading:
ini_set("gd.jpeg_ignore_warning", 1);
You then additionally need to check the return value from the imagecreatefromjpegDocs call:
$img = imagecreatefromjpeg($file);
if (!$img) {
printf("Failed to load jpeg image \"%s\".\n", $file);
die();
}
Also please see the potentially duplicate question:
the dreaded “Warning: imagecreatefromjpeg() : '/tmp/filename' is not a valid JPEG file in /phpfile.php on line xxx”
It has nearly the same error description like yours.
My solution for this issue: detect if imagecreatefromjpeg returns 'false' and in that case use imagecreatefromstring on file_get_contents instead.
Worked for me.
See code sample below:
$ind=0;
do{
if($mime == 'image/jpeg'){
$img = imagecreatefromjpeg($image_url_to_upload);
}elseif ($mime == 'image/png') {
$img = imagecreatefrompng($image_url_to_upload);
}
if ($img===false){
echo "imagecreatefromjpeg error!\n";
}
if ($img===false){
$img = imagecreatefromstring(file_get_contents($image_url_to_upload));
}
if ($img===false){
echo "imagecreatefromstring error!\n";
}
$ind++;
}while($img===false&&$ind<5);
Could you give any example of files that do / don't work?
According to http://www.php.net/manual/en/function.imagecreatefromjpeg.php#100338 blanks in remote filenamnes might cause issues.
In case you're using an URL as the source of the image, you will need to make sure the php setting allow_url_fopen is enabled.

Resize image at run time php

How can i preview an image on the run time?I have the uploader script and re size functionality.But image is not showing at the run time.I dont want to save iamge.Just resize and show at the run time.Image must show from memory not from directory .I was trying something like this :
if ($_FILES['myfile']['error'] == 0)
{
$theImageToResize=$_FILES['myfile']['name'];
$afterResize=Resize($theImageToResize);
echo $theImageToResize.'---->image after resize';
}
[just want to show image from the memory.Not from Directory];
Server Side Code :
$savefolder = 'images'; //upload dir
$max_size = 35000; //in bytes
// image types
$allowtype = array('bmp', 'gif', 'jpg', 'jpeg', 'gif', 'png');
$res = '';
// if is received a valid file
if (isset ($_FILES['myfile'])) {
$type = end(explode(".", strtolower($_FILES['myfile']['name'])));
if (in_array($type, $allowtype)) {
if ($_FILES['myfile']['size']<=$max_size*1000) {
if ($_FILES['myfile']['error'] == 0) {
$thefile = $savefolder . "/" . $_FILES['myfile']['name'];
$theImageToResize=$_FILES['myfile']['name'];
header('Content-type: image/jpeg');
$res = '<img src="'.$theImageToResize.'" />';
}
}
else { $res = 'The file <b>'. $_FILES['myfile']['name']. '</b> exceeds max Size <i>'. $max_size. 'KB</i>'; }
}
else { $res = 'The file <b>'. $_FILES['myfile']['name']. '</b> has not an allowed File Tyle..'; }
}
$res = urlencode($res);
echo '<body onload="parent.doneloading(\''.$res.'\')"></body>';
If you have the binary data that comprises the image in hand, you can use a data URI to echo an <img> tag with the image embedded, like this:
$imageData = /* binary image data */
$mimeType = 'image/jpg'; // or image/gif or image/png, must be accurate
printf('<img src="data:%s;base64,%s" alt="resized image" />',
$mimeType, base64_encode($imageData));
This allows you to output the resized image as part of a web page. If you want to display just the image, you can simply output a suitable header and then echo the binary data:
header('Content-type: image/jpg');
echo $imageData;
die;
$_FILES['myfile']['name']
contains file name, not location, use
$_FILES['myfile']['tmpname']
instead.
To resize read about imagecopyresampled PHP function - theres lot's of tutorials about PHP image resizing. To output the image use imagejpeg or imagepng function - this functions will output your image to browser. Do not forget about proper headers, such as
header('Content-type: image/jpeg');

Categories