Does imgjpeg function automatically take care of verification. - php

I am receiving multiple image files from android and I am using imgjpeg function. My question is do I have to verify that received file is an image file and is not corrupt or does this function take care of this verification (image + not corrupt) stuff.
Here is my code.
$data = file_get_contents("php://input");
$imageName = str_replace( array('[', ']', '"') ,"" ,$_SERVER['HTTP_IMAGE']);
if($imageName){
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/jpeg');
imagejpeg($im, $imageName, 100 );
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
}
else{
echo "Image name is not there";
}

Related

PHP creating video from string data

I'm trying to create a PHP web service for an android application which send a video as a string data and images as a string data both are base64 encoded to that PHP web service
So I create the image from the string as the following:
protected function saveImage($data, $image_ext, $path){
if(!empty($data)){
$data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im !== false) {
$name = 'img-'.str_random(4).'.'.$image_ext;
if ($image_ext == "png"){
imagepng($im, $path . $name, 9);
}else{
imagejpeg($im, $path . $name, 100);
}
return $path.$name;
} else {
return "";
}
}else{
return "";
}
}
Now I need to do that to the video string, is there any way to do that
Thanks for your help
I've figured out a way to do that I can only set the header to video/xxx and xxx = video type the use file_put_contents php function to store the video at the desired path
header('Content-Type: video/mp4');
$data = base64_decode($data);
$name = $path.'video-'.str_random(4).'.mp4';
$target_file = base_path()."/public/".$name;
file_put_contents($target_file,$data);
base_path() here to get the application root path at laravel

imagecreatefrompng() from base64 code?

is there a way to create an image with imagecreatefrompng() with this base 64 PNG code in PHP?
This works for me
<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
?>

Save byte to file with php

I have a c# program with some bitmap datatypes which i would like to upload to my web server with HTTP.
So i am thinking of converting the bitmap to the datatype bytes and then post it as text to the server, the sever would then save it as a image file.
How would i do this in PHP?
I am guessing something like this? but then how would i specify the save path location?
<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
?>
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
file_put_contents('img.png', base64_decode($data));

Convert binary byte array to image in PHP

I have a web service in Java which returns the requested file contents in byte[] (byte array) form. Sometimes these files are HTML files and sometimes they're images. There is no restriction of which file type it is. I'm looking for a way to convert this array to a valid image/string. My working for text files is below:
$bytes = getArray();
$string = implode(array_map("chr", $bytes));
echo $string;
This is the output of the echo $string;
‰PNG IHDR‘h6 pHYsÄÄ•+ OiCCPPhotoshop ICC profilexÚSgTSé=÷ÞôBKˆ€”KoR RB‹€‘&*! Jˆ!¡ÙQÁEEÈ ˆŽŽ€ŒQ,Š Øä!¢Žƒ£ˆŠÊûá{£kÖ¼÷æÍþµ×>ç¬ó³ÏÀ–H3Q5€©BàƒÇÄÆáä.# $p³d!sý#ø~<<+"À¾xÓÀM›À0‡ÿêB™\€„Àt‘8K€#zŽB¦#F€˜&S `ËcbãP-`'æÓ€ø™{[”! ‘ eˆDh;¬ÏVŠEX0fKÄ9Ø-0IWfH°·Àβ0Qˆ…){`È##x„™FòW<ñ+®ç*x™²<¹$9E[-qWW.(ÎI+6aaš#.Ây™24àóÌ ‘àƒóýxήÎÎ6Ž¶_-ê¿ÿ"bbãþåÏ«p#át~Ñþ,/³€;€mþ¢%îh^ u÷‹f²#µ éÚWópø~<ß5°j>{‘-¨]cöK'XtÀâ÷ò»oÁÔ(€hƒáÏwÿï?ýG %€fI’q^D$.Tʳ?ÇD *°AôÁ,ÀÁÜÁü`6„B$ÄÂBB d€r`)¬‚B(†Í°*`/Ô#4ÀQh†“p.ÂU¸=púažÁ(¼ AÈa!ÚˆbŠX#Ž™…ø!ÁH‹$ ɈQ"K‘5H1RŠT UHò=r9‡\Fº‘;È2‚ü†¼G1”²Q=ÔµC¹¨7„F¢Ðdt1š ›Ðr´=Œ6¡çЫhÚ>CÇ0Àè3Äl0.ÆÃB±8, “c˱"¬«Æ°V¬»‰õcϱwEÀ 6wB aAHXLXNØH¨ $4Ú 7 „QÂ'"“¨K´&ºùÄb21‡XH,#Ö/{ˆCÄ7$‰C2'¹I±¤TÒÒFÒnR#é,©›4H#“ÉÚdk²9”, +È…ääÃä3ää!ò[ b#q¤øSâ(RÊjJåå4åe˜2AU£šRݨ¡T5ZB­¡¶R¯Q‡¨4uš9̓IK¥­¢•Óhh÷i¯ètºÝ•N—ÐWÒËéGè—èôw †ƒÇˆg(›gw¯˜L¦Ó‹ÇT071ë˜ç™™oUX*¶*|‘Ê •J•&•*/T©ª¦ªÞªUóUËT©^S}®FU3Sã© Ô–«UªPëSSg©;¨‡ªg¨oT?¤~Yý‰YÃLÃOC¤Q ±_ã¼Æ c³x,!k «†u5Ä&±ÍÙ|v*»˜ý»‹=ª©¡9C3J3W³Ró”f?ã˜qøœtN ç(§—ó~ŠÞï)â)¦4L¹1e\kª–—–X«H«Q«Gë½6®í§¦½E»YûAÇJ'\'GgÎçSÙSݧ §M=:õ®.ªk¥¡»Dw¿n§î˜ž¾^€žLo§Þy½çú}/ýTýmú§õGX³$ÛÎ<Å5qo</ÇÛñQC]Ã#C¥a•a—á„‘¹Ñ<£ÕFFŒiÆ\ã$ãmÆmÆ£&&!&KMêMîšRM¹¦)¦;L;LÇÍÌÍ¢ÍÖ™5›=1×2ç›ç›×›ß·`ZxZ,¶¨¶¸eI²äZ¦Yn…Z9Y¥XUZ]³F­­%Ö»­»§§¹N“N«žÖgðñ¶É¶©·°åØÛ®¶m¶}agbg·Å®Ã“}º}ý= ‡Ù«Z~s´r:V:ޚΜî?}Åô–é/gXÏÏØ3ã¶Ë)ÄiS›ÓGgg¹sƒóˆ‹‰K‚Ë.—>.›ÆÝȽäJtõq]ázÒõ›³›Âí¨Û¯î6îiî‡ÜŸÌ4Ÿ)žY3sÐÃÈCàQåÑ?Ÿ•0k߬~OCOgµç#/c/‘W­×°·¥wª÷aï>ö>rŸã>ã<7Þ2ÞY_Ì7À·È·ËOÃož_…ßC#ÿdÿzÿѧ€%g‰A[ûøz|!¿Ž?:Ûeö²ÙíAŒ ¹AA‚­‚åÁ­!hÈì­!÷ç˜Î‘Îi…P~èÖÐaæa‹Ã~'…‡…W†?ŽpˆXÑ1—5wÑÜCsßDúD–DÞ›g1O9¯-J5*>ª.j<Ú7º4º?Æ.fYÌÕXXIlK9.*®6nl¾ßüíó‡ââã{˜/È]py¡ÎÂô…§©.,:–#LˆN8”ðA*¨Œ%òw%Ž yÂÂg"/Ñ6шØC\*NòH*Mz’쑼5y$Å3¥,幄'©¼L LÝ›:žšv m2=:½1ƒ’‘qBª!M“¶gêgæfvˬe…²þÅn‹·/•Ék³¬Y- ¶B¦èTZ(×*²geWf¿Í‰Ê9–«ž+Íí̳ÊÛ7œïŸÿíÂá’¶¥†KW-X潬j9²‰Š®Û—Ø(Üxå‡oÊ¿™Ü”´©«Ä¹dÏfÒféæÞ-ž[–ª—æ—n ÙÚ´ ßV´íõöEÛ/—Í(Û»ƒ¶C¹£¿<¸¼e§ÉÎÍ;?T¤TôTúT6îÒݵa×ønÑî{¼ö4ìÕÛ[¼÷ý>ɾÛUUMÕfÕeûIû³÷?®‰ªéø–ûm]­NmqíÇÒý#¶×¹ÔÕÒ=TRÖ+ëGǾþïw- 6 UœÆâ#pDyäé÷ ß÷ :ÚvŒ{¬áÓvg/jBšòšF›Sšû[b[ºOÌ>ÑÖêÞzüGÛœ499â?rýéü§CÏdÏ&žþ¢þË®/~øÕë×Îјѡ—ò—“¿m|¥ýêÀë¯ÛÆÂƾÉx31^ôVûíÁwÜwï£ßOä| (ÿhù±õSЧû“““ÿ˜óüc3-Û cHRMz%€ƒùÿ€éu0ê`:˜o’_ÅFìIDATxÚÁIoUàyËŒ§3žÅN°/Ávš BÛiQ¥J=ô€¢^*nHpAøHÜøœzABÀ$$$TRDQ$$C’62‰—8Nâ‰ñÄÛxÞìoæñ} qðûÁ^Ã%¤T]ÆXl5O¿ÿqǸüo:J²ª)ÊÖÃ{Ÿ}úØš9öÌ~çÞ›èñö»\ˆ)atð²ùõ“Ÿ..NgF£B(§•ÆÑIä;•bŽã\Ô¥J)¿V)®ä–êõÃѳm‹±øÕB‡ÜÀ8ŸL®ž=¯Ó(,&–…çvE>ÇM’ÎIÏuü‚þÉ£íoßùcw÷×?ŸwÍQ»Ý1Œa±£1ÃÖtц>ä(cqÓ·>úà=”’²²tÿöíF·óÍoÏ\׉CŸ"Œ9 0f²`2ªZ-¬ü°³;š«ù…ÀΦ¶šÉ6»ƒ¬¦jXÂæpŒH‰Â5m]¿þBVÿíµùî[FKMK«Çýé|k£¦¨RL#<™â0E{£VãÓZVOï7FSëã÷·oÞ¸ùùW_Ôª¥‡÷ïò¼à{!øùÉ—–íÙsWH+¼ÏOϪÅ%âÞÜ*è‹Š¾Ð1z⢬æ5Ïá¤xàêºf†Oÿn•u­Z)ëZ˜Ñ:³ÑÑÑêu>;íÞÜñÜñXÂù>Ùk­îåúÝŒ9¾šM“±9JÙ Äñt"h®X­”Pry5kœÛ;- T+}bõGãõJe.ºÔóFn¸ ‹›¯—=xwÉ^s6&6Ç(#xAí•l»×{ZßgIÐ䯓þÍ·6’„
But I have no idea how to do this for image files. I could somehow write this array to a file and load the image but my project doesn't allow me to do that. I have to do this on the fly.
If all you want to do is show the image to the user, you simply need to serve the right content header with the response:
if (substr($string, 0, 4) == "\x89PNG") header('Content-Type: image/png');
else if (substr($string, 0, 2) == "\xFF\xD8") header('Content-Type: image/jpeg');
else if (substr($string, 0, 4) == "GIF8") header('Content-Type: image/gif');
echo $string;
An image is really just a blob of data (like the 'string' you have) plus an indication that it's an image (in HTTP, that would be the MIME header). Since you already have the blob, all you need is the header to make the browser interpret it as an image.
Try
$body = file_get_contents('php://input');
and also refer PHP - get image from byte array
You mean like in the examples shown here: http://us.php.net/manual/en/function.imagecreatefromstring.php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
Using below code we can create image from byte array code.
$userId = $userid;
$encoded_image = $imgurl;
$upload_path = $_SERVER["DOCUMENT_ROOT"]."/projectName/uploads/";
$LoginUserDetails = $this->getUserDetails($userId);
if ($LoginUserDetails->profile_image != "") {
$dbimgname = $LoginUserDetails->profile_image;
unlink($upload_path .$dbimgname);
unlink($upload_path . 'thumb_img/' . $dbimgname);
}
$decoded_image = base64_decode($encoded_image);
$imgname = md5(uniqid()) . ".png";
file_put_contents($upload_path . $imgname, $decoded_image);
$thumbnail = $upload_path . "thumb_img/" . $imgname; // Set the thumbnail name
$actual = $upload_path . $imgname; // Set the actual image name
// Get new sizes
$upload_image = $upload_path.$imgname;
// print_r($actual); print_r($thumbnail); print_r($upload_image); die;
list($width, $height) = getimagesize($upload_image);
$newwidth = 196; // This can be a set value or a percentage of original size ($width)
$newheight = 196; // This can be a set value or a percentage of original size ($height)
// Load the images
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefrompng($upload_image);
//print_r($upload_image); print_r($source); die;
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); // Resize the $thumb image.
imagepng($thumb, $thumbnail, 100); // Save the new file to the location specified by $thumbnail
return $imgname;

Unable to rotate image with PHP's imagerotate

I continue to get this error after trying to retrieve an image from my DB and rotate it:
Warning: imagecreatefromstring() [function.imagecreatefromstring]: Data is not in a recognized format
Here is what I'm calling to convert the blob data back into an image for rotation:
$SQL="SELECT * FROM images WHERE id={$id}";
$rh = mysql_query($SQL);
$image=mysql_result($rh,0,"image");
$source_image=imagecreatefromstring($image);
$rotate_image = imagerotate($source_image, 90, 0);
Am I missing a step?
This is what I ended up doing for it to work:
$SQL="SELECT * FROM images WHERE id={$id}";
$rs = mysql_query($SQL);
//rotate image
$image=mysql_result($rs,0,"image");
$source_image=imagecreatefromstring($image);
$rotate_image = imagerotate($source_image, 270, 0);
ob_start();
imagejpeg($rotate_image, null, 100);
$image_bin = mysql_real_escape_string(ob_get_contents()); data.
ob_end_clean();
I recommend to store image data in base64. No problem with storing character and binary.
Then it's easy as that :
<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
?>
Source : http://php.net/manual/fr/function.imagecreatefromstring.php

Categories