How can I strip the data:image part from a base64 string of any image type in PHP

前端 未结 5 928
借酒劲吻你
借酒劲吻你 2021-01-04 18:29

I am currently doing the following to decode base64 images in PHP:

   $img = str_replace(\'data:image/jpeg;base64,\', \'\', $s[\'image\']);
   $img = str_rep         


        
相关标签:
5条回答
  • 2021-01-04 18:59

    I generete a image with javascript/kendo and send this by ajax to the server.

    preg_replace('#^data:image/[^;]+;base64,#', '', $s['image']); 
    

    it does not work in this case. in my case this code works better:

    $contentType  = mime_content_type($s['image']);
    $img = preg_replace('#^data:image/(.*?);base64,#i', '$2', $s['image']);
    
    0 讨论(0)
  • 2021-01-04 19:07

    Function file_get_contents remove header and use base64_decode function, so you get clear content image.

    Try this code:

    $img = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA0gA...';
    $imageContent = file_get_contents($img);
    
    0 讨论(0)
  • 2021-01-04 19:14

    You would have to test it but I think this solution should be slightly faster than Mihai Iorga's

    $offset = str_pos($s['image'], ',');
    $data = base64_decode(substr($s['image'], $offset));
    
    0 讨论(0)
  • 2021-01-04 19:14

    You can Regular expression for remove image or pdf data formate.

    data.replace(/^data:application\/[a-z]+;base64,/, "")
    
    0 讨论(0)
  • 2021-01-04 19:18

    You can use a regular expression:

    $img = preg_replace('#data:image/[^;]+;base64,#', '', $s['image']);
    

    if the text you are replacing is the first text in the image, adding ^ at the beginning of the regexp will make it much faster, because it won't analyze the entire image, just the first few characters:

    $img = preg_replace('#^data:image/[^;]+;base64,#', '', $s['image']);
    
    0 讨论(0)
提交回复
热议问题