Hướng dẫn php imagecreate to base64

I'm generating an image in PHP for use in a users avatar.

I start by hashing the username and then doing a hexdec[] conversion on various substrings of the hash to build up a set of RGB colours.

//create image
$avatarImage = imagecreate[250, 250];

// first call to imagecolorallocate sets the background colour
$background = imagecolorallocate[$avatarImage, hexdec[substr[$hash, 0, 2]], hexdec[substr[$hash, 2, 2]], hexdec[substr[$hash, 4, 2]]];

//write the image to a file
$imageFile = 'image.png';
imagepng[$avatarImage, $imageFile];

//load file contents and base64 encode
$imageData = base64_encode[file_get_contents[$imageFile]];

//build $src dataURI.
$src = 'data: ' . mime_content_type[$imageFile] . ';base64,' . $imageData;

Ideally I'd not use the intermediate step and would skip writing the image out onto disk, although I'm not sure how best to implement this?

I've tried passing $avatarImage directly to base64_encode[] but that expects a string so doesn't work.

Any ideas?

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    The base64_encode[] function is an inbuilt function in PHP which is used to convert any data to base64 encoding. In order to convert an image into base64 encoding firstly need to get the contents of file. This can be done with the help of file_get_contents[] function of PHP. Then pass this raw data to base64_encode[] function to encode.

    Required Function:

    • base64_encode[] Function The base64_encode[] function is an inbuilt function in PHP which is used to Encodes data with MIME base64. MIME [Multipurpose Internet Mail Extensions] base64 is used to encode the string in base64. The base64_encoded data takes 33% more space then original data.
    • file_get_contents[] Function The file_get_contents[] function in PHP is an inbuilt function which is used to read a file into a string. The function uses memory mapping techniques which are supported by the server and thus enhances the performances making it a preferred way of reading contents of a file.

    Input Image:

    Program:

    Output:

    iVBORw0KGgoAAAANSUhEUgAAApsAAAC4CAYAAACsNSfVAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJ
    cEhZcwAADsQAAA7EAZUrDhsAAAAZdEVYdFNvZnR3YXJdhfdsglgklAEFkb2JlIEltYWdlUmVhZHlxyWqwrwtwefd
    ...
    TeUsalQKBQKhUKhsBvK2FQoFAqFQqFQ2A1lbCoUCoVCoVAo7IYyNhUKhUKhUCgUdkMZmwqFQKBQKO0H0fxpZ1bfc

    Reference:

    • //php.net/manual/en/function.base64-encode.php
    • //php.net/manual/en/function.file-get-contents.php

    PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.

    Chuyển đến nội dung

    Có nhiều giải pháp để mã hoá hình ảnh, Encode Base64 là một trong số đó. Khi chuyển hình ảnh về dạng này ảnh được hiển thị trực tiếp từ Encode Base64 Image mà không qua URL ban đầu, điều này có nghĩa là sau khi bạn đã mã hoá thì bạn sẽ dùng code đã mã hoá này thay thế cho link ảnh ban đầu.

    Cách mã hoá này có ưu điểm là giúp bạn tránh được việc link ảnh bị die, hiển thị hình ảnh nhanh hơn và không sợ bị lỗi liên quan đến https. Tuy nhiên, nó cũng có nhược điểm là khi bạn dùng để hiển thị ảnh code in ra sẽ dài và nặng hơn.

    Một chút giới thiệu về cách mã hoá này thôi. Bây giờ ta tiến hành thực hiện, các bạn làm theo hướng dẫn bên dưới.

    //C1: dùng trên host
    $path = "myfolder/myimage.png"; 'duong-dan-ảnh-trên-host
    $type = pathinfo[$path, PATHINFO_EXTENSION];
    
    //C2: dùng từ URL get content về rồi mã hoá
    $path = "http[s]://mydomain.com/myimage.png"; 'duong-dan-ảnh-từ-web
    $headers = get_headers[$path, 1];
    $type = $headers["Content-Type"];
    
    $data = file_get_contents[$path];
    $base64 = 'data:image/' . $type . ';base64,' . base64_encode[$data];
    //KQ => ảnh đã được encode sang base64

    Code trên hoạt động bằng cách lấy content và header [để xem type ảnh] của ảnh rồi sao đó đưa vào phần mã hoá trả về kết quả $base64.

    DEMO:

    Các kết quả:

    Max value english = 195
    Max nonsense = 233
    

    Vì vậy, bạn có thể làm một cái gì đó như sau:

    if [ $maxDecodedValue > 200 ] {} //decoded string is Garbage - original string not base64 encoded
    
    else {} //decoded string is useful - it was base64 encoded
    

    Bạn có thể nên sử dụng giá trị trung bình [] của các giá trị được giải mã thay vì giá trị max [], tôi chỉ sử dụng hàm max [] trong ví dụ này vì đáng buồn là không có hàm ý nghĩa [] tích hợp sẵn trong PHP. Thước đo bạn sử dụng [trung bình, tối đa, v.v.] so với ngưỡng nào [ví dụ: 200] phụ thuộc vào hồ sơ sử dụng ước tính của bạn.

    Tóm lại, động thái chiến thắng duy nhất là không chơi. Tôi sẽ cố gắng tránh phải phân biệt base64 ngay từ đầu.

    25 hữu ích 0 bình luận chia sẻ

    [PHP 4, PHP 5, PHP 7, PHP 8]

    base64_decodeDecodes data encoded with MIME base64

    Description

    base64_decode[string $string, bool $strict = false]: string|false

    Parameters

    string

    The encoded data.

    strict

    If the strict parameter is set to true then the base64_decode[] function will return false if the input contains character from outside the base64 alphabet. Otherwise invalid characters will be silently discarded.

    Return Values

    Returns the decoded data or false on failure. The returned data may be binary.

    Examples

    Example #1 base64_decode[] example

    The above example will output:

    This is an encoded string
    

    winkelnkemper at googlemail dot com

    11 years ago

    If you want to save data that is derived from a Javascript canvas.toDataURL[] function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:

    walf

    6 years ago

    Base64 for URL parameters/filenames, that adhere to RFC 4648.
    Defaults to dropping the padding on encode since it's not required for decoding, and keeps the URL free of % encodings.



    for big $encoded strings, it's saver to use



    where 256 can be replaced by a sufficiently small modulo 4 natural.

    Tom

    15 years ago

    This function supports "base64url" as described in Section 5 of RFC 4648, "Base 64 Encoding with URL and Filename Safe Alphabet"

       

    Starson

    15 years ago

    To expand on Jes' post:

    The change took place between 5.0.5 and 5.1.0.  Exactly where I don't know or care.

    In short php

    This is the PHP equivalent to perl's unpack["u",___]. That is, you need to strip the 'begin' and 'end' lines from the typical uuencoded file.

    Klaus Fehrenbacher

    19 years ago

    this script can correct the bug

    dimagolov at yahoo dot com

    13 years ago

    Here is function to decode Base 62 [see //en.wikipedia.org/wiki/Base_62] string to number. It is used by MTA in message id, e.g. by Exim

    zmorris at zsculpt dot com

    14 years ago

    Here is a drop-in replacement for base64_decode[], based on a faster version of morgangalpin's code:

    alvaro at demogracia dot com

    13 years ago

    You can do partial decoding [e.g. from buffered input streams] if you choose a chunk length that is multiple of 4:



    4 encoded chars represent 3 original chars. The "=" character is used as padding.

    markandrewslade at gmail dot com

    6 years ago

    The docs don't make this explicitly clear, but if you omit `$strict` or set it to `false` then invalid characters in the encoded input will be silently ignored.

    Chủ Đề