The Wayback Machine - https://web.archive.org/web/20241125212339/https://www.geeksforgeeks.org/how-to-convert-an-image-to-base64-encoding-in-php/
Open In App

How to convert an image to base64 encoding in PHP?

Last Updated : 20 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

Example: In this example we retrieves an image from a URL using file_get_contents(), converts it into a string, encodes the image string to base64 format using base64_encode(), and then outputs the base64 string.

php
<?php 

// Get the image and convert into string
$img = file_get_contents(
'https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-22.png');

// Encode the image string data into base64
$data = base64_encode($img);

// Display the output
echo $data;
?>

Output:

iVBORw0KGgoAAAANSUhEUgAAApsAAAC4CAYAAACsNSfVAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJ
cEhZcwAADsQAAA7EAZUrDhsAAAAZdEVYdFNvZnR3YXJdhfdsglgklAEFkb2JlIEltYWdlUmVhZHlxyWqwrwtwefd
...
TeUsalQKBQKhUKhsBvK2FQoFAqFQqFQ2A1lbCoUCoVCoVAo7IYyNhUKhUKhUCgUdkMZmwqFQKBQKO0H0fxpZ1bfc

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.



Similar Reads

How to convert blob to base64 encoding using JavaScript ?
Blob in JavaScript is a fundamental data type representing bytes of data. It serves as the underlying structure for files and is supported by web browsers, capable of storing and retrieving data from memory. Blobs have specific sizes and file types like regular files and can be handled with Buffers, ideal for binary data storage such as images or f
2 min read
How Base64 Encoding and Decoding is Done in Node.js ?
Base64 encoding and decoding are when you need to encode binary data into a text format that can be easily transmitted over text-based protocols like HTTP. Node.js provides built-in methods for Base64 encoding and decoding, which can be easily performed using the Buffer class. Table of Content ApproachEncoding the original string to base64Decoding
3 min read
Explain the concept of URL Encoding & Describe the need for encoding in HTML
The URL (Uniform Resource Locator) is used to identify an internet resource on the WWW (World Wide Web). The below example demonstrates a URL. https://www.en.com:443/path/filename?r=1#fragment This URL contains: A protocol or scheme (https://)A domain prefix(sub-domain) (www.)A domain (en)A top-level domain (.com)A port (:443)A filepath (/path)A fi
3 min read
How to convert image into base64 string using JavaScript ?
In this article, we will convert an image into a base64 string using Javascript. The below approaches show the methods to convert an image into a base64 string using Javascript. ApproachHere we will create a gfg.js file which will include JavaScript code and one gfg.html file.Now we will put onchange on the input type and this will execute a functi
2 min read
Is embedding background image data into CSS as Base64 good or bad practice ?
One approach is to use external image files that are loaded separately by the browser. Another option is to embed the image data directly into the HTML or CSS code using Base64 encoding. In this article, we will explore whether embedding background image data into CSS as Base64 is a good or bad practice. Base64 Encoding: Base64 is a technique used
4 min read
How to Convert JSON to base64 in JavaScript ?
Base 64 is the encoding scheme that represents binary data in a printable ASCII format, commonly used for data serialization and transmission. Table of Content Using btoa functionUsing Manual ConversionUsing btoa functionIn this approach, we're using btoa to encode a UTF-8 string representation of a JSON object. First, the JSON data is converted to
2 min read
How to Convert Base64 to File in JavaScript?
In web development, Base64 encoding is often used to represent binary data, such as images or files, with a string of ASCII characters, sometimes you may be required to change this Base64 string back into a file for instance for file uploads, downloads, or processing in the browser, this article aims to discuss different ways of converting Base64 s
2 min read
How to Convert Base64 to Blob in JavaScript?
Working with files and data in web applications often involves dealing with binary data. One common scenario is converting a Base64 string into a Blob object, which can then be used in various ways, such as creating downloadable files or uploading images to a server. This article will guide you through converting a Base64 string to a Blob in JavaSc
4 min read
How To Convert Base64 to JSON String in JavaScript?
There could be situations in web applications, where there is a need to decode the data from Base64 format back into its original JSON format. It generally happens when one has to transmit data over the network where Base64 encoding is well suited for encoding binary data. In this article, we will see how one can convert Base64 strings into JSON-fo
2 min read
Convert base64 String to ArrayBuffer In JavaScript
A Base64 string represents binary data in an ASCII string format by translating it into a radix-64 representation. Often used to encode binary data in text-based formats like JSON or HTML, it needs to be converted back into its original binary format for further processing. An ArrayBuffer in JavaScript is a generic, fixed-length binary data buffer,
2 min read
JavaScript | Encode/Decode a string to Base64
To encode or decode strings in JavaScript, we can use the built-in functions provided by the language. These functions help in encoding special characters in a URL or decoding encoded strings back to their original form. 1. btoa() MethodThis method encodes a string in base-64 and uses the "A-Z", "a-z", "0-9", "+", "/" and "=" characters to encode t
6 min read
How to display Base64 images in HTML ?
Base64 is a widely used method for encoding binary data, such as images, into ASCII text. This enables embedding binary data, such as images, directly into HTML without needing separate image files. In the context of web development, Base64 encoding is often used to improve page performance, security, and compatibility by reducing the number of ext
4 min read
How to validate if input in input field has base64 encoded string using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. If In a certain input field only base 64 encoded string are allowed i.e there not allowed any other form of string which not const
4 min read
How to Detect Character Encoding using mb_detect_encoding() function in PHP ?
Character encoding is an essential aspect of handling text in various programming languages including PHP. Different character encodings such as UTF-8, ISO-8859-1, and ASCII represent characters differently. Finding the correct character encoding of text is important to ensure proper data processing and display. In PHP, the mb_detect_encoding() fun
2 min read
Convert an Image into Grayscale Image using HTML/CSS
A grayscale image is an image that displays only shades of gray, without any color, representing varying levels of light intensity. You can easily convert an image to grayscale in HTML/CSS by applying the filter: grayscale(100%) property to desaturate the colors. The grayscale() filter in CSS can take values between 0 and 1. Here's what these value
2 min read
Web TextEncoder API | TextEncoder encoding property
In HTML there is a TextEncoder Interface which has a property encoding which tells us about the encoding algorithm used by the encoder. It can only have the value that is utf-8. Syntax: var b = encoder.encoding; Return Value: It returns the name of the encoding algorithm. Example: <!DOCTYPE html> <html> <head> <title> Web Te
1 min read
HTTP headers | Content-Encoding
The HTTP headers Content-encoding is used to compress the media type. It informers the server which encoding the user will supported. It sends the information to the Accept-encoding. The server selects any one of the proposals, uses it and informs the client of its choice with the Content-Encoding response header. Syntax: Content-Encoding: gzip | c
2 min read
HTTP headers | Transfer-Encoding
The HTTP Transfer-Encoding is a response-type header that performs as the hop-by-hop header, the hop-by-hop header connection is the single transport-level connection must not be re-transmitted. This header is performing between two nodes (single transport-level connection). If there is multi-node connection then have to use other Transfer-Encoding
2 min read
How to specify the character encoding used in an external script file in HTML5 ?
To specify the character encoding used in an external script file in HTML5 we use <script> charset attribute. The charset attribute specifies the character encoding for the HTML document when used by the <meta> element. The charset attribute specifies the character encoding used in an external script file when used by the <script>
1 min read
How to set character encoding for document in HTML5 ?
In this article, we will learn how to set character encoding for document in HTML5. Character encoding is a method of defining a mapping between bytes and text. To display an HTML document correctly, we must choose a proper character encoding. The different types of character encoding include: ASCII Character Set: It is the first ever character enc
2 min read
How to fix “No character encoding declared at document level” in HTML Document ?
This article intends to solve the “No character encoding declared at document level” issue in your HTML program. So, before getting to the solution, we need to understand what this issue means. And for that first, we need to know about character encoding in HTML. What is character encoding in HTML? Character encoding is a system used to represent c
5 min read
Understanding HTML Form Encoding: URL Encoded and Multipart Forms
HTML forms contain two encodings, the URL Encoded Forms and the multipart Forms. The encoding in an HTML form is determined by an attribute named 'enctype'. This attribute can have three values: AttributeDescriptionapplication/x-www-form-urlencodedRepresents a URL-encoded form. Default enctype for sending form data.multipart/form-dataRepresents a m
3 min read
How to specify the encoding type of form data in HTML ?
To specify the encoding type of form data in HTML, you use the "enctype" attribute within the <form> tag. This attribute determines how form data should be encoded before it is sent to the server when the form is submitted. It's essential to choose the appropriate encoding type based on the content of the form data to ensure that it is transm
2 min read
How to Get File Character Encoding in Node.js ?
Character encoding is essential when working with text files, as it determines how characters are represented in bytes. Different files may use different encodings, such as UTF-8, ASCII, or ISO-8859-1. Determining the character encoding of a file in Node.js can help ensure proper reading and processing of the file's content. Why Is Character Encodi
2 min read
HTML URL Encoding
A Uniform Resource Locator (URL) is simply the address of a website to access the website content like www.geeksforgeeks.org. But certain characters are allowed to be used in the URL like alphabets A-Z and a-z, numbers 0-9, and a few special characters. They can be used as it is but the rest of the characters that are not in this list are used afte
4 min read
HTTP headers | Accept-Encoding
The HTTP headers Accepts-Encoding is usually a comparison algorithm of request header. All the HTTP client used to tell the server which encoding or encodings it supports. Then the server will respond in any of the supporting encoding formats. The server selects any one of the proposals, uses it and informs the client of its choice with the Content
2 min read
How to convert a PDF document to a preview image in PHP?
Converting a PDF document into a set of images may not sound that fun, but it can have a few applications. As the content from images cannot be copied that easily, the conversion makes the document strictly 'read-only' and brings an extra layer of protection from plagiarism. The images may also come in handy when you need some ready-made slides for
6 min read
How to specify an image as a server-side image-map in HTML ?
In image mapping, an image is specified with certain set of coordinates inside the image which act as hyperlink areas to different destinations. It is different from an image link since in image linking, an image can be used to serve a single link or destination whereas in a mapped image, different coordinates of the image can serve different links
1 min read
How to slice image specified by border-image-source in CSS ?
In this article, we will see how to add a border image as a slice image using CSS. To make the border slice image, the border-image-slice property is used. This property divides or slices an image specified by the border-image-source property. The border-image-slice property divides a given image into - 9 regions4 corners4 edgesA middle region The
2 min read
Which attribute is used to specify an alternate text for an image, if the image is not loaded properly in HTML ?
In this article, we will discuss the attribute that is used to specify an alternate text for an image, if an image is not loaded properly in HTML. The <img> alt attribute is used to specify the alternate text for an image. It is useful when the image is not displayed. It is used to give alternative information for an image. Syntax: <img al
1 min read
three90RightbarBannerImg