Compare string to binary photo base64encoded PHP - php

Im converting a photo to binary text. How come when I copy the output and the try to compare it against itself the two dont match? here is part of it
if(isset($_FILES['file'])) {
$image = $_FILES['file']['tmp_name'];
$data = fopen ($image, 'rb');
$size=filesize ($image);
$contents= fread ($data, $size);
fclose ($data);
$encoded= base64_encode($contents);
$code = "/9j/4AAQSkZJRgAB ...." //etc. the output I previously got from photo
if($code == $encoded){echo 'success';} // but they dont match

I got it. It had to do with my text editor adding a line break because the string was so long. I just deleted the space and they match.

Related

Convert base64 string image from upload to SVG without writing file

I have canvas generated jpg in base64 string uploaded by ajax to php. I have the following working code to do the data:image/jpeg;base64 to svg conversion.
//Uploaded is a string start from data:image/jpeg;base64,...(not a .jpg)
$b64 = (isset($_POST['img']) ? $_POST['img'] : null);
if($b64){
$b64= str_replace('data:image/jpeg;base64,', '', $b64);
$b64= str_replace(' ', '+', $b64);
$im = new Imagick();
$im->readImageBlob(base64_decode($b64));
$im->trimImage(2000);
$im->setImageFormat( "ppm" );
$im->writeImage( "out.ppm" );
$cmd = exec("potrace out.ppm -s -o out.svg 2>&1", $output, $e);
}
However, I found that writing file is a very slow process and make my file system messy. I want to eliminate the writing process by piping the command so that no writing file is needed, but I am not familiar with command line.
Imagick limits the input string up to 5000 characters, so I cannot do like this as it fails once b64 is too long.
exec("convert inline:".$b64." ppm:- | potrace -s -o out.svg");
So,I tried to do the following to wrap the string to a text file but it fails as the content is different and without the "data:image/jpeg;base64" at the beginning. I don't want to write a text file everytime too.
if(strlen($b64)> 4000){
$arr = str_split($b64, 4000);
foreach ($arr as $key => $a) {
$test = exec("echo ".$a." >> out.b64 2>&1", $output, $e);
}
}
Q1: Any chance I can wrap the b64 string into a temp text file as an input to imagick?
Q2: I want to echo back the svg xml instead of download it as a file. And again, this writes a new file although this is faster. I hope there is a method not outputing as a file but as a variable or object like thing in php.
Any suggestions are welcome. Thank you.
Try this.,
$base64_str = str_replace('data:image/png;base64,', '', $b64);
$base64_str = str_replace(' ', '+', $base64_str);
$decoded = base64_decode($base64_str);
$targetPath ="../your target path/";
$png_url ="../your target path/"."product-".strtotime('now').".png";
$image_name ="product-".strtotime('now').".png";
$result = file_put_contents($png_url, $decoded);
I'm sorry to respond to such an old question, but I'm a little confused, why are you trying to convert a base64 encoded JPG (a raster image format) to SVG (a vector image format)?
That won't work, and best case scenario, the SVG will just contain a reference to the original JPG. Is that what you were looking to do?
I am not sure if you are looking for this:
to get base64_encode of an uploaded image (tmp image):
$filename = $_FILES['image']['tmp_name'];
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
$encoded_img = base64_encode($data);

PHP base64_docode saves corrupt image

I am sending base64 encoded image to PHP from my android app. Sometime it stores full image (4KB) and sometime (3KB) (Same Image). when I use URL in picasso, image with 4KB size works fine but image with 3KB size does not load it shows decode error.
This is my PHP code (which sometime works)
$encodedImage = str_replace(' ','+',$_POST['encodedProfileImage']);
$data = base64_decode($encodedImage);
$file = 'Pics/'. uniqid() . '.png';
$success = file_put_contents($file, $data);
$BASE_URL = 'http://domain.com/TestApp/';
I then do SQL operation in PHP to store image path. Is there any chance that next code operation is done on half decoded image(which is corrupt).
You need to remove the part that says data:image/png;base64, at the beginning of the image data. The actual base64 data comes after that.
Use below function:-
function base64_to_png($base64_string, $output_file) {
$ifp = fopen($output_file, "wb");
$data = explode(',', $base64_string);
fwrite($ifp, base64_decode($data[1]));
fclose($ifp);
return $output_file;
}
If you want to use str_replace function then may be below way work. I am not sure :)
$fname = filter_input(INPUT_POST, "name");
$encodedImage = filter_input(INPUT_POST, "image");
$encodedImage = str_replace('data:image/png;base64,', '', $encodedImage);
$encodedImage = str_replace(' ', '+', $encodedImage);
$encodedImage = base64_decode($encodedImage);
file_put_contents($fname, $encodedImage);
print "Image has been saved!";
Hope it will help you :)

php take image, rotate and save rotated image on server

Want to take image from own server rotate certain angle and save the image.
Image file $filename = 'kitten_rotated.jpg'; With echo '<img src='.$filename.'>'; i see the image.
Then
$original = imagecreatefromjpeg($filename);
$angle = 90.0;
$rotated = imagerotate($original, $angle, 0);
Based on this https://stackoverflow.com/a/3693075/2118559 answer trying create image file
$output = 'google.com.jpg';
If i save the same image with new file name, all works
file_put_contents( $output, file_get_contents($filename) );
But if i try to save rotated image, then file_put_contents(): supplied resource is not a valid stream resource.
file_put_contents( $output, $rotated );
Here https://stackoverflow.com/a/12185462/2118559 read $export is going to be a GD image handle. It is NOT something you can simply dump out to a file and expect to get a JPG or PNG image.. but can not understand how to use the code in that answer.
How to create image file from $rotated?
Tried to experiment, based on this http://php.net/manual/en/function.imagecreatefromstring.php
$fh = fopen( 'some_name.png' , 'w') or die("can't open file");
fwrite($fh, $data );
fclose($fh);
Does it means that need something like
$data = base64_encode($rotated);
And then write in new file?
I have not tested this, but I think you need to encode the image as base 64 first.
If you check the string from any Image URL, you'd see data:image/png;base64, preceding the hash. Prepending this to your image string and saving.
Here is a function that may help, based on what you already have:
// Function settings:
// 1) Original file
// 2) Angle to rotate
// 3) Output destination (false will output to browser)
function RotateJpg($filename = '',$angle = 0,$savename = false)
{
// Your original file
$original = imagecreatefromjpeg($filename);
// Rotate
$rotated = imagerotate($original, $angle, 0);
// If you have no destination, save to browser
if($savename == false) {
header('Content-Type: image/jpeg');
imagejpeg($rotated);
}
else
// Save to a directory with a new filename
imagejpeg($rotated,$savename);
// Standard destroy command
imagedestroy($rotated);
}
// Base image
$filename = 'http://upload.wikimedia.org/wikipedia/commons/b/b4/JPEG_example_JPG_RIP_100.jpg';
// Destination, including document root (you may have a defined root to use)
$saveto = $_SERVER['DOCUMENT_ROOT']."/images/test.jpg";
// Apply function
RotateJpg($filename,90,$saveto);
If you want to save image just use one of GD library functions: imagepng() or imagepng().
imagerotate() returns image resource so this is not something like string.
In your case just save rotate image:
imagejpg($rotated, $output);
And now You can use $output variable as your new filename to include in view like before:
echo '<img src='.$output.'>';
Don't forget to include appropriate permissions in directory where You're saveing image.

unlink base64 encoded image not working

hi guys ive created a base64 encoded image captured with web cam now i convert the .png to .jpg all works fine but now i get two images on server both .png and .jpg how do i go about deleting the .png or is their a way to convert to jpg without saving .png image to disk thanx here my code
$rawData = $_POST['imgBase64'];
$filteredData = explode(',', $rawData);
$unencoded = base64_decode($filteredData[1]);
$randomName = rand(1000, 99999999999);
//Create the image
$fp = fopen('user/'.$randomName.'.png', 'w');
fwrite($fp, $unencoded);
//convert image from png to jpg
$image = imagecreatefrompng('user/'.$randomName.'.png');
imagejpeg($image, 'user/'.$randomName.'.jpg', 80);
unlink($fp);
ive tried it with
unlink($image);
unlink($_SERVER['DOCUMENT_ROOT'] . "/user/.$randomName.'.png'");
imagedestroy($fp);
imagedestroy($image);
Use the function unlink() but passing the file name to it instead of the file handler.
So from your example it would be:
EDIT: You might need to close the file first:
fclose( $fp );
unlink( 'user/'.$randomName.'.png' );
as far as i understand all you need is:
$data = base64_decode( $_POST['imgBase64']);
// image resource from your string
$image = imagecreatefromstring($data);
imagejpeg($image, 'user/'.$randomName.'.jpg', 80);

PHP: How would you check if the result string of file_get_contents() is a JPG image?

I am using file_get_contents() to pull some images from a remote server and I want to confirm if the result string is a JPG/PNG image before further processing, like saving it locally and create thumbs.
$string = file_get_contents($url);
How would you do this?
I got from this answer the starting bits for a JPG image. So basically what you could do is to check whether the starting bits are equal or not:
$url = 'http://i.stack.imgur.com/Jh3mC.jpg?s=128&g=1';
$jpg = file_get_contents($url);
if(substr($jpg,0,3) === "\xFF\xD8\xFF"){
echo "It's a jpg !";
}
You can use getimagesize()
$url = 'http://www.geenstijl.nl/archives/images/HassVivaCatFight.jpg';
$file = file_get_contents($url);
$tmpfname = tempnam("/tmp", "FOO");
$handle = fopen($tmpfname, "w");
fwrite($handle, $file);
$size = getimagesize($tmpfname);
if(($size['mime'] == 'image/png') || ($size['mime'] == 'image/jpeg')){
//do something with the $file
echo 'yes an jpeg of png';
}
else{
echo 'Not an jpeg of png ' . $tmpfname .' '. $size['mime'];
fclose($handle);
}
I just tested it so it works. You need to make a temp file becouse the image functions work with local data and they only accept local directory path like 'C:\wamp2\www\temp\image.png'
If you do not use fclose($handle); PHP will automatically delete tmp after script ended.
You can use
exif_imagetype()
to evaluate your file. Please do check the php manual.
Edited :
Please note that PHP_EXIF must be enabled. You can read more about it here
Maybe standart PHP function exif_imagetype() http://www.php.net/manual/en/function.exif-imagetype.php

Categories