Save base64 encoded image as JPG instead of PNG - php

I am saving a base64 encoded image using this simple PHP script...
define('UPLOAD_DIR', 'upload/');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
file_put_contents($file, $data);
This works great but the image is always a PNG. I have tried changing the extension to JPG in the hopes that it would work but it doesn't.
Do I need to save it as a PNG first then convert it to a JPG?

Yes, you must convert the image into JPG at first.

Related

how can I decode base64 to .jpg

I can decode base64 to PNG, but when I try to decode to JPG I got the problem.
Code to decode png
$image = $request['profile_image']; // your base64 encoded
$image = str_replace('data:image/png;base64,', '', $image);
$image = str_replace(' ', '+', $image);
$imageName = 'aaaa'.'.'.'png';
\File::put(public_path() .'/admin_assets/assets/images/users/' . $imageName, base64_decode($image));
Code decode to jpg
$image = $request['profile_image']; // your base64 encoded
$image = str_replace('data:image/jpeg;base64,', '', $image);
$image = str_replace(' ', '+', $image);
$imageName = 'aaaa'.'.'.'jpg';
\File::put(public_path() .'/admin_assets/assets/images/users/' . $imageName, base64_decode($image));
The result from the second code
http://prnt.sc/oysxqn
You can use this function for that base64_decode_image() (It's GitHub link I wrote a function)
Function return array (file and type), but if is image format not allowed it fill return false.
Usage
$AllowedFormats = array('jpg', 'png'); // Here we declare allowed formats
$ProfilImage = $request['profile_image'];
$Image = base64_decode_image($ProfilImage, $AllowedFormats);
// Here we checking if is returned array or not
if(!is_array($Image )){
echo 'Wrong image format';
die(); // if is image format not allowed it will stop scrip and throw an error
}
$type = $Image['type']; // type is file extension as well
$DecodedImage = $Image['file']; // Decoded image file
$ImageName = 'whet-every-you-wanna.'.$type;
// Then you can upload your image
\File::put(public_path() .'/admin_assets/assets/images/users/' . $imageName, $DecodedImage);

PHP Decode Base64 Image to png and save in current directory

I know there are so many solutions for decode base64 image. But any of them didn't work for me.
I have the Base64 image data and i need to convert it to a png file and save it to the local directory.
I tried the following code which i got from here. But it didnt work for me. Please help me to get this done..
define('UPLOAD_DIR', 'images/');
$base64string = "data:image/png;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBB...";
$img = $base64string;
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . 'txtimg.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
When i execute the script its getting the error message Unable to save. Then i gave full permission for the users. But still no luck.
I tried to save a simple text file through file_put_contents() ; it worked.
I'm using IIS 8 on Windows Azure Server.

Decoding base64 string gives a black rectangle image

I'm trying to get an image from canvas and save it with my php script. But when the script proceedes, I got a simple black rectangle instead of my canvas image (web-cam snapshot).
Here is my code:
$img = $base64Img;
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = "photo/" . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
What is the purpose of this line:
$img = str_replace(' ', '+', $img);
Don't think it is necessary.
Otherwise all seems fine.
I usually use php explode to isolate the data:
$exploded = explode(',', $img);
$base64 = $exploded[1];
$data = base64_decode($base64);
But str_replace should also do the job.
Maybe the error is in the code that loads the image?
UPDATE
Purpose of that line is to encode the white space in the base64 data.
This is also mentioned in this comment on php.net.
Probably it would be better to use the PHP function urlencode in such cases.
$data = base64_decode($data);
This line is probably causing the issues in this, since the data is not used as a data url but saved to a file directly.

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);

upload video from iphone device to server in php

I am working on the project which includes uploading image and video of user from iphone device. I am handling the backend with PHP. For uploading images I am getting the base64encode string and I have use following code to upload the image -
$str = $data['pictureurl']; // base64encode string
$newVar = base64_decode($str);
define('UPLOAD_DIR', 'userimages/');
$img = $str;
$date = strtotime(date("m-d-y H:i:s"));
$img = str_replace('data1:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data1 = base64_decode($img);
$file = UPLOAD_DIR . strtolower($data['firstName']).strtolower($data['lastName']). "_".$userId . '.png';
$totalpath = $path.$file;
#chmod('userimages/', 0777);
$success = file_put_contents($file, $data1);
From this code, image gets uploaded to the server in specified directory properly with .png extension. May I use the same code for uploading video making the file type .flv or .mov? I have tried it, but file gets placed in the folder with 0 bytes of data. What could be the problem? or is there any another solution to upload such file ?

Categories