Home  >  Q&A  >  body text

In PHP, how to encode the generated verification code image into base64?

PHP Server Android Client

I need to encode the verification code image generated by the server into base64

Note: does not generate and display images, but directly encodes the generated image resources into base64

so how to do? ? ? ? ? ? ?

阿神阿神2673 days ago1589

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-05-27 17:44:38

    Main functions:

    function base64EncodeImage ($image_file) {
        $base64_image = '';
        $image_info = getimagesize($image_file);
        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
        $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
        return $base64_image;
    }

    demo:

    <?php
    $img = 'icon.jpg';
    $base64_img = base64EncodeImage($img);
     
    echo '<img src="' . $base64_img . '" />';
    echo '<img src="' . $img . '" />';
     
    function base64EncodeImage ($image_file) {
        $base64_image = '';
        $image_info = getimagesize($image_file);
        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
        $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
        return $base64_image;
    }
    ?>

    Implementation:

    ================ Supplements =================

    GD to base64:

    ob_start (); 
    imagejpeg ($img);
    $image_data = ob_get_contents (); 
    ob_end_clean (); 

    It is estimated that ob_get_contents is used to obtain buffer data.
    Refer to the original text: Original text link

    PS:
    Please make good use of Google Baidu.

    reply
    0
  • 为情所困

    为情所困2017-05-27 17:44:38

    If the generated verification code is saved on the server side, use file_get_contents to get the image and then base64encode the result and output it.

    reply
    0
  • Cancelreply