Can I safely assume that the size (in bytes) of a PNG image file created with the following PHP code:
$f = fopen("newImageFile.png", 'w');
$content = base64_decode(substr($dataURL, strpos($dataURL, ',') + 1));
fwrite($f, $content);
where $dataURL is posted from HTML's canves.toDataURL(), exactly equals strlen($content)?
You could use getimagesizefromstring() If you have a newer php version.
But since you are decoding you could use this as well.
$uri = 'data://application/octet-stream;base64,' . base64_encode($data);
getimagesize($uri);
Related
I had base64 encoded data.
Look my code, please.
First of all, see my code.
$data = "data:image/png;base64,iVBORw0KGgoAAAA..........";
$image_array_1 = explode(";", $data);
$image_array_2 = explode(",", $image_array_1[1]);
$data = base64_decode($image_array_2[1]);
$imageName = uniqid().time().".png";
I want to set an extension .png to complete my file so that I can count this file extension by laravel method $image->getClientOriginalExtension() and others laravel file methods.
sorry for miss spell of language.
Hope I make you understand.
This works, although I cannot say if it's the best way to go about it. It's a full working example with a 1x1 black pixel png image. This assumes you already removed the data:image/png;base64, portion from the image data.
$data = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR
42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=');
// Create a temp file and write the decoded image.
$temp = tmpfile();
fwrite($temp, $data);
// Get the path of the temp file.
$tempPath = stream_get_meta_data($temp)['uri'];
// Initialize the UploadedFile.
$imageName = uniqid().time().".png";
$file = new \Illuminate\Http\UploadedFile($tempPath, $imageName, null, null, true);
// Test if the UploadedFile works normally.
echo $file->getClientOriginalExtension(); // Shows 'png'
$file->storeAs('images', 'test.png'); // Creates image in '\storage\app\images'.
// Delete the temp file.
fclose($temp);
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);
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 :)
So I'm receiving an image in base64 encoding. I want to decode the image and upload it in a specific directory. The encoded file is an image and I'm using $file = base64_decode($base64_string); to decode it. Uploading it via file_put_contents('/uploads/images/', $file); always results in failed to open stream: No such file or directory error.
So, how do I take the decoded string, and upload it on a specific path?
Thanks.
Your path is wrong.
/uploads/images
is checking for a folder in the / directory called uploads. You should specify the full path to the folder:
/var/www/vhosts/MYSITE/uploads/images
I had the same problem and finally solved using this:
<?php
$file = base64_decode($base);
$photo = imagecreatefromstring($file);
//create a random name
$RandomStr = md5(microtime());
$name = substr($RandomStr, 0, 3);
$name .= date('Y-m-d');
$name .= '.jpg';
//assign name and upload your image
imagejpeg($photo, 'images/'.$name, 100);
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