Convert Image into base64 by JS

1:20 PM

When we want to upload a image in on server in cordova/ionic some time we need to convert the image in base64 formate . I've write a function which will convert your image in base64.

function convertImgToBase64URL(url, callback, outputFormat) {
 var img = new Image();
 img.crossOrigin = 'Anonymous';
 img.onload = function() {
  var canvas = document.createElement('CANVAS'),
      ctx = canvas.getContext('2d'),
      dataURL;
  canvas.height = this.height;
  canvas.width = this.width;
  ctx.drawImage(this, 0, 0);
  dataURL = canvas.toDataURL(outputFormat);
  callback(dataURL);
  canvas = null;
 };
 img.src = url;
 return url;
}

How to use :

convertImgToBase64URL(img, function(base64Img) {
 console.log(base64Img);// this is your base64 converted image     
});

Post this image on server(IONIC)

$http.post(server_url,[base64Img])

Handel this image in PHP :

   
$params = json_decode(file_get_contents('php://input'), true); get the post image

$img = imageUploadByBase64($params[0]);// this is the saved image path with image name

function imageUploadByBase64($img) {
 $randomImgName = date('Y-m-d_H-i-s').'_'.rand(0, 6000).'.png';
 $image = base64_to_jpeg($img, 'uploads/' . $randomImgName);// you need to create a directory withh name 'uploads'
 return $image;
}

function base64_to_jpeg($base64_string, $output_file) {
 $ifp = fopen($output_file, "wb");
 $data = explode(',', $base64_string);
 fwrite($ifp, base64_decode($data[1]));
 fclose($ifp);
 return $output_file;
}

You Might Also Like

1 comments