With the continuous advancement of information technology and the rise of Web2.0, people's demand for multimedia information is getting higher and higher. Picture formats such as PNG, JPG, and GIF have become an indispensable part of our lives. As PHP code is the most widely used language in web development, how to convert binary to images has become one of the basic skills that programmers need to master.
1. Conversion between binary and hexadecimal
Before learning how to convert binary into pictures, we need to master the mutual conversion between binary and hexadecimal. Taking 8 binary bits as a group, that is, one byte as a unit, it can represent an integer between 0 and 255; and every four binary bits correspond to a hexadecimal number, that is, one byte uses two hexadecimal digits. Number representation. For example, the binary number 11001000 corresponds to the hexadecimal number 0xC8, and the hexadecimal number 0x50 corresponds to the binary number 01010000.
We can use PHP's sprintf function to convert an integer in any base into a base string with a specified number of digits. For example, to convert the integer represented by $int into an 8-digit binary string, you can use the following code:
$bin = sprintf("%08b", $int);
Similarly, to convert the integer represented by $int into a 2-digit hexadecimal string For strings, you can use the following code:
$hex = sprintf("%02x", $int);
2. Convert binary to image
Next, we will learn how to convert binary string to PNG image. The PNG image format supports multiple colors of transparency without compression loss, so it is widely used in web development.
First, we need to define a $binary variable to save the byte array converted from the binary string. For a 24-bit true color (RGB) PNG image, its pixel value consists of 3 bytes of RGB values. Therefore, during the conversion process, the binary string needs to be cut into groups of 3 bytes. point. After the segmentation is completed, each group of bytes can be used as the value of the three RGB channels to generate the pixel array of the PNG image. After generating the pixel array, use the imagepng function to write the pixel array into a PNG image file to generate a PNG image.
The complete code is as follows:
//将二进制字符串转为PNG图片 function binaryToPNG($binary, $width, $height) { //计算像素数组的长度(每个像素由3个字节的RGB值组成) $len = strlen($binary); $pixelLen = $len / 3; //通过imagecreatetruecolor函数创建一个PNG图片的像素数组 $im = imagecreatetruecolor($width, $height); //遍历二进制字符串,将每一组3个字节的值分别作为RGB三通道的值,并生成像素数组 for ($i = 0; $i <p>Finally, we need to convert the binary string into a PHP byte array before we can operate it in the binaryToPNG function. For a binary string in the shape of "0100101010101001010...", you can use the following code to convert it into a PHP byte array: </p><pre class="brush:php;toolbar:false">$binary = pack("B*", $binaryString);
3. Convert the image to binary
Corresponding to converting binary to pictures, we also need to convert pictures into binary strings. In this process, you can use the imagecreatefrompng function to read the PNG image as a pixel array, then use the imagecolorat function to obtain the RGB value of each pixel, and finally splice the RGB values into a binary string. The complete code is as follows:
//将PNG图片转为二进制字符串 function pngToBinary($file) { //通过imagecreatefrompng函数将PNG图片读取为像素数组 $im = imagecreatefrompng($file); $width = imagesx($im); $height = imagesy($im); $binary = ''; //遍历像素数组,获取每个像素的RGB值,拼接成一组二进制字符串 for ($y = 0; $y > 16) & 0xFF; $g = ($rgb >> 8) & 0xFF; $b = $rgb & 0xFF; $binary .= sprintf("%02x%02x%02x", $r, $g, $b); } } return $binary; }
4. Summary
This article details how to convert a binary string into a PNG image, and how to convert a PNG image into a binary string. Through learning, we can not only master the mutual conversion method between binary and hexadecimal in PHP, but also how to perform image operations in PHP code. In actual development, these basic skills can help us better complete multimedia-related operations and provide strong support for Web development.
The above is the detailed content of How to convert binary to image in php. For more information, please follow other related articles on the PHP Chinese website!

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.