Create/display image from dataURL

后端 未结 3 1290
面向向阳花
面向向阳花 2021-01-05 14:46

is it possible to create and display a picture file from dataURL received by POST? Something like:



        
相关标签:
3条回答
  • 2021-01-05 15:12

    Yes, try:

    <img alt="Base64 Image" src="data:image/png;base64,{$imgstr}" />
    

    Edit: make sure you clean up your $_POST, so people do not insert dangerous junk...

    0 讨论(0)
  • 2021-01-05 15:20

    You must set correct header before echo.

    header( 'Content-Type: image/jpeg' );
    
    0 讨论(0)
  • 2021-01-05 15:30

    If e.g. your input is

    // Red dot graphic, stolen from Wikipedia
    $imgstr = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
    

    Then you can do what you want with

    // Grab the MIME type and the data with a regex for convenience
    if (!preg_match('/data:([^;]*);base64,(.*)/', $imgstr, $matches)) {
        die("error");
    }
    
    // Decode the data
    $content = base64_decode($matches[2]);
    
    // Output the correct HTTP headers (may add more if you require them)
    header('Content-Type: '.$matches[1]);
    header('Content-Length: '.strlen($content));
    
    // Output the actual image data
    echo $content;
    die;
    
    0 讨论(0)
提交回复
热议问题