How to convert base64 in to image in php? [duplicate] - php

This question already has answers here:
How to save a PNG image server-side, from a base64 data URI
(17 answers)
Closed 3 years ago.
I am trying to convert my base64 image string to an image file. This is my Base64 string:
http://pastebin.com/ENkTrGNG
Using following code to convert it into an image file:
function base64_to_jpeg( $base64_string, $output_file ) {
$ifp = fopen( $output_file, "wb" );
fwrite( $ifp, base64_decode( $base64_string) );
fclose( $ifp );
return( $output_file );
}
$image = base64_to_jpeg( $my_base64_string, 'tmp.jpg' );
But I am getting an error of invalid image, whats wrong here?

The problem is that data:image/png;base64, is included in the encoded contents. This will result in invalid image data when the base64 function decodes it. Remove that data in the function before decoding the string, like so.
function base64_to_jpeg($base64_string, $output_file) {
// open the output file for writing
$ifp = fopen( $output_file, 'wb' );
// split the string on commas
// $data[ 0 ] == "data:image/png;base64"
// $data[ 1 ] == <actual base64 string>
$data = explode( ',', $base64_string );
// we could add validation here with ensuring count( $data ) > 1
fwrite( $ifp, base64_decode( $data[ 1 ] ) );
// clean up the file resource
fclose( $ifp );
return $output_file;
}

An easy way I'm using:
file_put_contents($output_file, file_get_contents($base64_string));
This works well because file_get_contents can read data from a URI, including a data:// URI.

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.
Just strip everything up to and including base64, (before calling base64_decode() on the data) and you'll be fine.

maybe like this
function save_base64_image($base64_image_string, $output_file_without_extension, $path_with_end_slash="" ) {
//usage: if( substr( $img_src, 0, 5 ) === "data:" ) { $filename=save_base64_image($base64_image_string, $output_file_without_extentnion, getcwd() . "/application/assets/pins/$user_id/"); }
//
//data is like: data:image/png;base64,asdfasdfasdf
$splited = explode(',', substr( $base64_image_string , 5 ) , 2);
$mime=$splited[0];
$data=$splited[1];
$mime_split_without_base64=explode(';', $mime,2);
$mime_split=explode('/', $mime_split_without_base64[0],2);
if(count($mime_split)==2)
{
$extension=$mime_split[1];
if($extension=='jpeg')$extension='jpg';
//if($extension=='javascript')$extension='js';
//if($extension=='text')$extension='txt';
$output_file_with_extension=$output_file_without_extension.'.'.$extension;
}
file_put_contents( $path_with_end_slash . $output_file_with_extension, base64_decode($data) );
return $output_file_with_extension;
}

That's an old thread, but in case you want to upload the image having same extension-
$image = $request->image;
$imageInfo = explode(";base64,", $image);
$imgExt = str_replace('data:image/', '', $imageInfo[0]);
$image = str_replace(' ', '+', $imageInfo[1]);
$imageName = "post-".time().".".$imgExt;
Storage::disk('public_feeds')->put($imageName, base64_decode($image));
You can create 'public_feeds' in laravel's filesystem.php-
'public_feeds' => [
'driver' => 'local',
'root' => public_path() . '/uploads/feeds',
],

if($_SERVER['REQUEST_METHOD']=='POST'){
$image_no="5";//or Anything You Need
$image = $_POST['image'];
$path = "uploads/".$image_no.".png";
$status = file_put_contents($path,base64_decode($image));
if($status){
echo "Successfully Uploaded";
}else{
echo "Upload failed";
}
}

This code worked for me.
<?php
$decoded = base64_decode($base64);
$file = 'invoice.pdf';
file_put_contents($file, $decoded);
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>

$datetime = date("Y-m-d h:i:s");
$timestamp = strtotime($datetime);
$image = $_POST['image'];
$imgdata = base64_decode($image);
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
$temp=explode('/',$mime_type);
$path = "uploads/$timestamp.$temp[1]";
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded->>> $timestamp.$temp[1]";
This will be enough for image processing. Special thanks to Mr. Dev Karan Sharma

Related

Base64 image string into image file using PHP

I need code to convert a base64 image string into an image file and write into local directory using PHP. I tried:
function user_profile_photo(){
$input = urldecode(file_get_contents('php://input'));
$received = json_decode($input, true);
$user_id = $received['user_id'];
$img = $received['imagecode'];
$imagedata = base64_decode($img);
$image_path='uploads/images/'.$user_id;
$path = '/var/www/html/empengapp/uploads/images/'.$user_id;
if (!file_exists($path)) {
mkdir($path, 0755, true);
}
$new_name = date('ymd').time().'.jpg';
$pathwithfile = '/var/www/html/empengapp/uploads/images/'.$user_id.'/'.$new_name;
$success = file_put_contents($pathwithfile, $imagedata);
var_dump($imagedata);exit;
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($resp, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
->_display();
exit;
}//end of function user_profile_photo
It is writing a file with given extension, but when you try to open file it shows an invalid file error.
I figure it out the solution.
$pathwithfile = 'your file path with image name';//e.g '/uploads/test.jpg'
$ifp = fopen( $pathwithfile, 'wb' );
// split the string on commas
// $data[ 0 ] == "data:image/png;base64"
// $data[ 1 ] == <actual base64 string>
$data = explode( ',', $imagedata );
$success = fwrite( $ifp, base64_decode( $data[ 1 ] ) ); // clean up the file resource
fclose( $ifp );
I was sending over the API to PHP server. You need to encode your image base64 string and your image base64 string must include "data:image/jpeg;base64". We are splitting it on PHP server But don't think to send image base54 without "data:image/jpeg;base64".
But remember one thing you have to use image base64 including

How to get image from bytes array in php?

How to get image from bytes array in php ? i have string of byte array and i want to generate a image.
I have tries this code below.
$arrayData = array(
'status' => 404,
'message' => 'Not Found'
);
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$img = isset($obj['image']) ? $obj['image'] : '';
print_r($img); die;
$filename = $finalimage . '.' . 'jpg';
$filepath = base_url().'uploads/apifiles'.$filename;
file_put_contents($filepath, $finalimage);
Try this code below
$image_string = 'byte_strng';
$data = base64_decode($image_string);
$im = imagecreatefromstring($data);
header('Content-Type: image/jpeg');
imagejpeg($im);
imagedestroy($im);

yii2 REST api for file upload

Im trying to upload a file image/file type from mobile app and store that image in the backend. Im using Yii2 framework API to do this. And im using postman to check the API. Im running the below in my action.
/*Uploading documents*/
public function actionUploading_doc() {
$uploads = \yii\web\UploadedFile::getInstanceByName('upfile');
print_r($uploads);exit;
if (empty($uploads)){
return "Must upload at least 1 file in upfile form-data POST";
}
foreach ($uploads as $file){
$filename = time() . $image->name;
$path = "uploads/" . $filename;
$file->saveAs($path);
}
}
When i run this as POST method from postman.. and print the value of $uploads im getting empty value. It mean its not coming to controller.
Please help me in solving this.
For me this is what i did without the UploadFile class
/*Uploading documents*/
public function actionUploading() {
$uploads = \yii\web\UploadedFile::getInstanceByName('upfile');
\yii::$app->request->enableCsrfValidation = false;
$filename = $uploads->name;
$path = "http://localhost/projects/YiiRestful/api/web/uploads/".$filename;
$putdata = fopen("php://input", "r");
// make sure that you have /web/upload directory (writeable)
// for this to work
$path = "uploads/".$filename;
$fp = fopen($path, "w");
while ($data = fread($putdata, 1024))
fwrite($fp, $data);
/* Close the streams */
fclose($fp);
fclose($putdata);
}
I would try something like this... (not tested)
public function actionUploadingDoc() { // good practice to use camel case for methods
$uploads = \yii\web\UploadedFile::getInstances('upfile');
if (empty($uploads)){
return false;
// handle error reporting somewhere else
}
$path = 'uploads/'; // set your path
foreach ($uploads as $upload){
$filename = $path . time() .'_'. $upload->name ;
$upload->saveAs($filename);
}
return true;
}
You can use base64 string to uplod. define function inside controller like this
public function base64_to_jpeg($base64_string, $output_file) {
$path="your/real/path/";
// open the output file for writing
$ifp = fopen( $path.$output_file, 'wb' );
// split the string on commas
// $data[ 0 ] == "data:image/png;base64"
// $data[ 1 ] == <actual base64 string>
$data = explode( ',', $base64_string );
if(count($data)>1) {
$dataText=$data[ 1 ];
} else {
$dataText=$base64_string;
}
// we could add validation here with ensuring count( $data ) > 1
fwrite( $ifp, base64_decode( $dataText ) );
// clean up the file resource
fclose( $ifp );
return $output_file;
}
And use inside action as
public function actionUpload(){
$imgName=md5(uniqid()).'.jpg';
$this->base64_to_jpeg($base64_string, $imgName);
}

convert base64 image to jpg then upload to server not working

I am new to base64 and I have never needed to convert it so I am not sure what is going on here. I have my base64 string in $socialmedia_image. I create a random file name with rand. I plug it into the function which I got off stack and....nothing. It does not convert or transfer over with move_uploaded_file and I have no idea who to check for an error.
Can someone tell me what I am doing wrong?
///// base64 string /////
$socialmedia_image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg.....";
$rand = rand(000000000000000,999999999999999);
$output_file = $rand.".jpg";
$socialmedia_image = base64_to_jpeg( $socialmedia_image, $output_file );
function base64_to_jpeg($base64_string, $output_file) {
$ifp = fopen( $output_file, 'w' );
$data = explode( ',', $base64_string );
fwrite( $ifp, base64_decode( $data[ 1 ] ) );
fclose( $ifp );
return $output_file;
}
move_uploaded_file($socialmedia_image, "../tickets/attachments/".$output_file);
How about that?
file_put_contents($output_file, $data);

File format lost when I use mozilla browser to download files saved in database

I am uploading files and save them in database but when I download them,with the header returned when I download ; the file format and fileName are lost in Mozilla while chrome is working correctly. I want to know what wrong with my codes. I supplied a segment of code for uploading and another for downloading.
For Ms word document, the returned header says the document is Microsoft Excel Worksheet (47.4 KB).
Have a look at my codes.
//Getting details of file to be uploaded
$fileName =$suffix.$_FILES['report']['name'];
$tmpName = $_FILES['report']['tmp_name'];
$fileSize = $_FILES['report']['size'];
$fileType = $_FILES['report']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
};
`
` $documentData=array(
// 'periodId' => $this->input->post('period',true),
'reporter' => $this->session->userdata("userId"),
'documentName' => $fileName,
'documentType' => $fileType,
'documentSize' => $fileSize,rtv## Heading ##
'document'=> $content,
'date' => date("Y/m/d"));`
$this->document_model->save($documentData);
Then I try to download the file using the following segment of codes:
` public function download(){
$key=$this->uri->segment(3);
$query = "SELECT documentName, documentType, documentSize, document "
"FROM report_documents WHERE documentId='$key'"; `
` $result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) =mysql_fetch_array($result);
header("Content-type: $type");
header("Content-length: $size");
header("Content-Disposition: attachment; filename=$name");
echo $content;
exit;
}
`

Categories