Base64文字列を画像ファイルに変換しますか? [重複] 質問する

Base64文字列を画像ファイルに変換しますか? [重複] 質問する

Base64 イメージ文字列をイメージ ファイルに変換しようとしています。これが私の Base64 文字列です:

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。何が問題なのでしょうか?

ベストアンサー1

問題は、data:image/png;base64,エンコードされたコンテンツに が含まれていることです。これにより、base64 関数でデコードすると無効な画像データが生成されます。次のように、文字列をデコードする前に関数内でそのデータを削除します。

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; 
}

おすすめ記事