Home Backend Development PHP Problem How to convert binary to image in php

How to convert binary to image in php

Apr 04, 2023 am 10:41 AM

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);
Copy after login

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);
Copy after login

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 < $pixelLen; $i++) {
        $r = ord($binary[$i * 3]);
        $g = ord($binary[$i * 3 + 1]);
        $b = ord($binary[$i * 3 + 2]);
        imagesetpixel($im, $i % $width, floor($i / $width), imagecolorallocate($im, $r, $g, $b));
    }
    //使用imagepng函数将像素数组写入PNG图片文件中,从而生成PNG图片
    header(&#39;Content-Type:image/png&#39;);
    imagepng($im);
    imagedestroy($im);
}
Copy after login

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:

$binary = pack("B*", $binaryString);
Copy after login

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 = &#39;&#39;;
    //遍历像素数组,获取每个像素的RGB值,拼接成一组二进制字符串
    for ($y = 0; $y < $height; $y++) {
        for ($x = 0; $x < $width; $x++) {
            $rgb = imagecolorat($im, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            $binary .= sprintf("%02x%02x%02x", $r, $g, $b);
        }
    }
    return $binary;
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

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.

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

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.

PHP Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

PHP API Rate Limiting: Implementation strategies. PHP API Rate Limiting: Implementation strategies. Mar 26, 2025 pm 04:16 PM

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

PHP Input Validation: Best practices. PHP Input Validation: Best practices. Mar 26, 2025 pm 04:17 PM

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.

PHP CSRF Protection: How to prevent CSRF attacks. PHP CSRF Protection: How to prevent CSRF attacks. Mar 25, 2025 pm 03:05 PM

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.

See all articles