Play base64 PHP image processing

Play base64 php image processing

  
    public function testimg () 
    { 
         
        $ img_dir = ' ../public/1.jpg ' ; // source image path 
        $ = $ base64_string the this -> imgToBase64 ($ img_dir); // the image to a base64 about 
        echo ' <IMG the src = " ' . $ base64_string. ' "> ' ;        // Display in the form of a picture 
     
        $ path = ' ../public/2.jpg ' ; // Set the path of the newly generated picture, please read this file before operation present 
        $ = base64_string the explode ( ' , ' ,$base64_string); // Intercept data: image / png; base64, the character after the comma 
        $ data = base64_decode ($ base64_string [ 1 ]); // Use base64_decode to decode the intercepted characters 
        $ rs = file_put_contents ($ path, $ data) ; // Write file and save 
        if ($ rs <= 0 ) { 
            $ this- > error ( ' Image conversion failed ' ); 
        } 
       
    } 
    
/ * * 
 * Get the Base64 encoding of the image (URL is not supported) 
 * @param $ img_file incoming local picture address 
 * @return string 
 * / 
public function imgToBase64 ($ img_file) { 
    $ img_base64 = '' ;
     if(file_exists ($ img_file)) { 
        $ app_img_file = $ img_file; // Image path 
        $ img_info = getimagesize ($ app_img_file); // Get the size and type of the image 

        // echo '<pre>'. print_r ($ img_info, true). '</ pre> <br>'; 
        $ fp = fopen ($ app_img_file, " r " ); // Whether the image can be read 

        if ($ fp) { 
            $ filesize = filesize ($ app_img_file); 
            $ content = fread ($ fp, $ filesize); 
            $ file_content = chunk_split (base64_encode ($ content)); // base64 encoding 
            switch ($ img_info [2]) {           //判读图片类型
                case 1: $img_type = "gif";
                    break;
                case 2: $img_type = "jpg";
                    break;
                case 3: $img_type = "png";
                    break;
            }

            $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;// Base64 encoding of synthetic pictures 

        } 
        fclose ($ fp); 
    } 

    return $ img_base64; // return base64 of pictures 
}

 

Guess you like

Origin www.cnblogs.com/baker95935/p/12671878.html