Skip to content

Instantly share code, notes, and snippets.

@henrytriplette
Last active September 11, 2018 15:41
Show Gist options
  • Save henrytriplette/8149da22d7d17d1d0fe1758a10463a47 to your computer and use it in GitHub Desktop.
Save henrytriplette/8149da22d7d17d1d0fe1758a10463a47 to your computer and use it in GitHub Desktop.

Save render as png

Main render function

var getImageData = false // Turn to true to launch export

function render(time) {

  // Pdf export
  if (getImageData === true) {
    // Set renderer to fixed width/height
    camera.aspect = 800 / 600
    camera.updateProjectionMatrix()
    renderer.setSize(800, 600)

    renderer.render(scene, camera)

    var imgData = renderer.domElement.toDataURL()
    getImageData = false

    saveImg(imgData)

    need_to_update_size = true
  }
}

function saveImg (imgData) {
  var current_sku = createSku(configurator_sku)

  // Save image
  jQuery.ajax({
    type: 'POST',
    url: getUrl + 'assets/inc/elements/saveElementsImage.php',
    data: {
      'imgData': imgData,
      'current_sku': current_sku
    },
    success: function (msg) {
      return console.log(msg)
    },
    error: function (msg) {
      return console.error('Error Print - Errore nell\'elaborazione della richiesta.', msg)
    }
  })

}

saveElementsImage.php

<?php
ob_start();
session_start();

$insert = ($_POST);

$ds = DIRECTORY_SEPARATOR;

if (empty($insert['imgData'])) die('No data provided, exiting');
if (empty($insert['current_sku'])) die('No SKU provided, exiting');

// echo '<pre>';
// print_r($insert['current_sku']);
// echo '</pre>';

  $filename = clean_sku($insert['current_sku']);
  $filenpath =  '../../../../configurator_output/'.$filename.'.png';

  // Save Image to server
  $output = base64_to_jpeg($insert['imgData'], $filenpath);

  // Return filename
  echo $filename;

function clean_sku($string) {
   $string = str_replace(' ', '_', $string); // Replaces all spaces with _.
   $string = str_replace('-', '_', $string); // Replaces all - with _
   $string = preg_replace('/[^A-Za-z0-9\-]/', '_', $string); // Removes special chars and replace with _.

   return preg_replace('/_+/', '_', $string); // Replaces multiple _ with single one.
}

// Save image
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;
}

?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment