title: base64 image to image file with Symfony and VichUploader
body: <p>In symfony, I have an entity <code>Program</code>, which has the attribute <code>image</code>. Uploading images, naming them and putting them in the right directory is done with the <code>VichUploaderBundle</code>. The entity looks like this:</p>
  
  <pre><code>//...
  
  /**
   * NOTE: This is not a mapped field of entity metadata, just a simple property.
   *
   * @Assert\Image(
   *     maxSize="5M",
   *     mimeTypesMessage="The file you tried to upload is not a recognized image file"
   *    )
   * @Vich\UploadableField(mapping="program_image", fileNameProperty="imageName")
   *
   * @var File
   */
  private $image;
  
  /**
   * @ORM\Column(type="string", length=191, nullable=true)
   */
  private $imageName; 
  
  //...
  </code></pre>
  
  <p>Now I wish for images to be processed before they are uploaded, which I have done with some JS that returns a base64 string. I put this string in a hidden input field, <code>base64Image</code>. I then retrieve this string in my controller and try to make it into an image that I can save to my entity like so:</p>
  
  <pre><code>if ($form-&gt;isSubmitted() &amp;&amp; $form-&gt;isValid()) {
      $program = $form-&gt;getData();
  
      $base64String = $request-&gt;request-&gt;get('base64Image');
      $decodedImageString = base64_decode($base64String);
  
      $program-&gt;setImage($decodedImageString);
  
  //etc.....
  </code></pre>
  
  <p>The program occurs with the last line. <code>$decodedImageString</code> is actually another string that first needs to be created into a file. I have looked into <code>file_put_contents</code> to create a file as describer <a href="https://stackoverflow.com/questions/15153776/convert-base64-string-to-an-image-file">here</a>, but with no luck. </p>
  
  <blockquote>
    <p>The filename cannot be empty</p>
  </blockquote>
  
  <p>Is the error I receive. Also I don't know if this would work with the <code>VichUploaderBundle</code> and perhaps the answer in that question is also outdated. Any suggestions on what I could do? </p>
  
  <p><strong>Edit:</strong>
  Got the converting and uploading working with the following code: </p>
  
  <pre><code>define('UPLOAD_DIR', 'images/');
  $img = $request-&gt;request-&gt;get('base64Image');
  $img = str_replace('data:image/jpeg;base64,', '', $img);
  $img = str_replace(' ', '+', $img);
  $data = base64_decode($img);
  $file = UPLOAD_DIR . uniqid() . '.jpeg';
  $success = file_put_contents($file, $data);
  print $success ? $file : 'Unable to save the file.';
  </code></pre>
  
  <p>Now I just need to load the VichUploaderBundle config somehow, or maybe not use that altogether perhaps. </p>