- Saved searches
- Use saved searches to filter your results more quickly
- License
- wuyumin/File2base64
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- base64_encode
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- User Contributed Notes 37 notes
- Преобразование изображения в Base64 на PHP
- Результат:
- Преобразование изображения в Base64 на PHP
- Результат:
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
License
wuyumin/File2base64
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
base64 files are used for embedding in web pages.
composer require wuyumin/file2base64
require __DIR__ . '/../vendor/autoload.php'; use File2base64\File2base64; $file2base64 = new File2base64(); # $file2base64 = new File2base64(['bmp' => 'image/bmp']); $file2base64->toFile('file2base64.png', 'file2base64.txt'); # echo $file2base64->toBase64('file2base64.png');
(tips:Laravel 5.5+ can ignore step 2、3,version 5.5+ support to register automatically)
- Composer install composer require wuyumin/file2base64
- (ServiceProvider)add the follow line to the section providers of config/app.php
File2base64\Laravel\ServiceProvider::class, - (Facades)add the follow line to the section aliases of config/app.php (optional)
‘File2base64’ => File2base64\Laravel\Facade::class,
img src pl-s">data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" alt="">
You can init for other type use array.
$file2base64 = new File2base64([‘bmp’ => ‘image/bmp’]);
base64_encode
Эта кодировка предназначена для корректной передачи бинарных данных по протоколам, не поддерживающим 8-битную передачу, например, для отправки тела письма.
Данные, закодированные base64 занимают на 33% больше места по сравнению с оригинальными данными.
Список параметров
Возвращаемые значения
Кодированные данные в виде строки.
Примеры
Пример #1 Пример использования base64_encode()
Результат выполнения данного примера:
0K3RgtC+INC30LDQutC+0LTQuNGA0L7QstCw0L3QvdCw0Y8g0YHRgtGA0L7QutCw
Смотрите также
- base64_decode() — Декодирует данные, закодированные MIME base64
- chunk_split() — Разбивает строку на фрагменты
- convert_uuencode() — Кодирует строку в формат uuencode
- » RFC 2045 раздел 6.8
User Contributed Notes 37 notes
For anyone interested in the ‘base64url’ variant encoding, you can use this pair of functions:
function base64url_encode ( $data ) <
return rtrim ( strtr ( base64_encode ( $data ), ‘+/’ , ‘-_’ ), ‘=’ );
>
function base64url_decode ( $data ) <
return base64_decode ( str_pad ( strtr ( $data , ‘-_’ , ‘+/’ ), strlen ( $data ) % 4 , ‘=’ , STR_PAD_RIGHT ));
>
?>
gutzmer at usa dot net’s ( http://php.net/manual/en/function.base64-encode.php#103849 ) base64url_decode() function doesn’t pad longer strings with ‘=’s. Here is a corrected version:
function base64url_encode ( $data ) return rtrim ( strtr ( base64_encode ( $data ), ‘+/’ , ‘-_’ ), ‘=’ );
>
function base64url_decode ( $data ) return base64_decode ( strtr ( $data , ‘-_’ , ‘+/’ ) . str_repeat ( ‘=’ , 3 — ( 3 + strlen ( $data )) % 4 ));
>
// proof
for( $i = 0 , $s = » ; $i < 24 ; ++ $i , $s .= substr ( " $i " , - 1 ))$base64_encoded = base64_encode ( $s );
$base64url_encoded = base64url_encode ( $s );
$base64url_decoded = base64url_decode ( $base64url_encoded );
$base64_restored = strtr ( $base64url_encoded , ‘-_’ , ‘+/’ )
. str_repeat ( ‘=’ ,
3 — ( 3 + strlen ( $base64url_encoded )) % 4
);
echo » $s
$base64url_decoded
$base64_encoded
$base64_restored
$base64url_encoded
» ;
>
?>
In PHP 7, the padding issue with base64_decode() is no more — the following is totally fine:
function base64_encode_url($string) return str_replace([‘+’,’/’,’=’], [‘-‘,’_’,»], base64_encode($string));
>
function base64_decode_url($string) return base64_decode(str_replace([‘-‘,’_’], [‘+’,’/’], $string));
>
Checked here with random_bytes() and random lengths:
Base64 encoding of large files.
Base64 encoding converts triples of eight-bit symbols into quadruples of six-bit symbols. Reading the input file in chunks that are a multiple of three bytes in length results in a chunk that can be encoded independently of the rest of the input file. MIME additionally enforces a line length of 76 characters plus the CRLF. 76 characters is enough for 19 quadruples of six-bit symbols thus representing 19 triples of eight-bit symbols. Reading 57 eight-bit symbols provides exactly enough data for a complete MIME-formatted line. Finally, PHP’s default buffer size is 8192 bytes — enough for 143 MIME lines’ worth of input.
So if you read from the input file in chunks of 8151 (=57*143) bytes you will get (up to) 8151 eight-bit symbols, which encode as exactly 10868 six-bit symbols, which then wrap to exactly 143 MIME-formatted lines. There is no need to retain left-over symbols (either six- or eight-bit) from one chunk to the next. Just read a chunk, encode it, write it out, and go on to the next chunk. Obviously the last chunk will probably be shorter, but encoding it is still independent of the rest.
while(! feof ( $input_file ))
$plain = fread ( $input_file , 57 * 143 );
$encoded = base64_encode ( $plain );
$encoded = chunk_split ( $encoded , 76 , «\r\n» );
fwrite ( $output_file , $encoded );
>
?>
Conversely, each 76-character MIME-formatted line (not counting the trailing CRLF) contains exactly enough data for 57 bytes of output without needing to retain leftover bits that need prepending to the next line. What that means is that each line can be decoded independently of the others, and the decoded chunks can then be concatenated together or written out sequentially. However, this does make the assumption that the encoded data really is MIME-formatted; without that assurance it is necessary to accept that the base64 data won’t be so conveniently arranged.
Unfortunately my «function» for encoding base64 on-the-fly from 2007 [which has been removed from the manual in favor of this post] had 2 errors!
The first led to an endless loop because of a missing «$feof»-check, the second caused the rare mentioned errors when encoding failed for some reason in larger files, especially when
setting fgets($fh, 2) for example. But lower values then 1024 are bad overall because they slow down the whole process, so 4096 will be fine for all purposes, I guess.
The error was caused by the use of «empty()».
Here comes the corrected version which I have tested for all kind of files and length (up to 4,5 Gb!) without any error:
$fh = fopen ( ‘Input-File’ , ‘rb’ );
//$fh2 = fopen(‘Output-File’, ‘wb’);
if (! $eof ) <
if (! feof ( $fh )) <
$row = fgets ( $fh , 4096 );
> else <
$row = » ;
$eof = true ;
>
>
if ( $cache !== » )
$row = $cache . $row ;
elseif ( $eof )
break;
$b64 = base64_encode ( $row );
$put = » ;
if ( strlen ( $b64 ) < 76 ) <
if ( $eof ) <
$put = $b64 . «\n» ;
$cache = » ;
> else <
$cache = $row ;
>
> elseif ( strlen ( $b64 ) > 76 ) <
do <
$put .= substr ( $b64 , 0 , 76 ). «\n» ;
$b64 = substr ( $b64 , 76 );
> while ( strlen ( $b64 ) > 76 );
$cache = base64_decode ( $b64 );
if ( $put !== » ) <
echo $put ;
//fputs($fh2, $put);
//fputs($fh2, base64_decode($put)); // for comparing
>
>
Преобразование изображения в Base64 на PHP
Преобразование файла в Base64-изображение для вставки тег или CSS background производится по следующему формату:
Для теста возьмем маленькое изображение: Для него в PHP нужно получить MIME, прочитать файл и закодировать полученные данные функцией base64_encode() . Т.к. функция getimagesize() не актуальна для SVG файлов, для них придется сделать исключение.
Результат:
Преобразование изображения в Base64 на PHP
Преобразование файла в Base64-изображение для вставки тег или CSS background производится по следующему формату:
Для теста возьмем маленькое изображение: Для него в PHP нужно получить MIME, прочитать файл и закодировать полученные данные функцией base64_encode() . Т.к. функция getimagesize() не актуальна для SVG файлов, для них придется сделать исключение.
Результат: