将Base64string转换为图像文件?

我试图将我的base64图像string转换为图像文件。 这是我的Base64string:

http://pastebin.com/ENkTrGNG

使用以下代码将其转换为图像文件:

function base64_to_jpeg( $base64_string, $output_file ) { $ifp = fopen( $output_file, "wb" ); fwrite( $ifp, base64_decode( $base64_string) ); fclose( $ifp ); return( $output_file ); } $image = base64_to_jpeg( $my_base64_string, 'tmp.jpg' ); 

但是我得到一个invalid image错误,这里怎么了?

问题是data:image/png;base64,包含在编码的内容中。 这会在base64函数解码时导致无效的图像数据。 在解码string之前删除函数中的数据,就像这样。

 function base64_to_jpeg($base64_string, $output_file) { // open the output file for writing $ifp = fopen( $output_file, 'wb' ); // split the string on commas // $data[ 0 ] == "data:image/png;base64" // $data[ 1 ] == <actual base64 string> $data = explode( ',', $base64_string ); // we could add validation here with ensuring count( $data ) > 1 fwrite( $ifp, base64_decode( $data[ 1 ] ) ); // clean up the file resource fclose( $ifp ); return $output_file; } 

您需要删除图像数据开始部分的data:image/png;base64, 。 实际的base64数据在那之后。

只要剥离一切,包括base64, (在调用base64_decode()之前的数据),你会没事的。

也许这样

 function save_base64_image($base64_image_string, $output_file_without_extension, $path_with_end_slash="" ) { //usage: if( substr( $img_src, 0, 5 ) === "data:" ) { $filename=save_base64_image($base64_image_string, $output_file_without_extentnion, getcwd() . "/application/assets/pins/$user_id/"); } // //data is like: data:image/png;base64,asdfasdfasdf $splited = explode(',', substr( $base64_image_string , 5 ) , 2); $mime=$splited[0]; $data=$splited[1]; $mime_split_without_base64=explode(';', $mime,2); $mime_split=explode('/', $mime_split_without_base64[0],2); if(count($mime_split)==2) { $extension=$mime_split[1]; if($extension=='jpeg')$extension='jpg'; //if($extension=='javascript')$extension='js'; //if($extension=='text')$extension='txt'; $output_file_with_extension=$output_file_without_extension.'.'.$extension; } file_put_contents( $path_with_end_slash . $output_file_with_extension, base64_decode($data) ); return $output_file_with_extension; } 
 if($_SERVER['REQUEST_METHOD']=='POST'){ $image_no="5";//or Anything You Need $image = $_POST['image']; $path = "uploads/$image_no.png"; file_put_contents($path,base64_decode($image)); echo "Successfully Uploaded"; }