Home Backend Development PHP Tutorial PHP extension development notes (10) Customize the IO function in the libpng library to write pictures into memory

PHP extension development notes (10) Customize the IO function in the libpng library to write pictures into memory

Aug 08, 2016 am 09:21 AM
null png size write

When developing this QR code extension dcode, the generated QR code png image needs to be returned to the caller in the form of a string instead of directly generating a file. This is more convenient because there is no need to operate the file. The operation of files is completely left to the user.

The libpng library is used to generate images. For documentation about libpng, you can go to png documentation here. When I used this library to compile my extension on Ubuntu14.04, I still had a small problem: png_create_write_struct in Unknown on line 0 on ubuntu 14. After searching on the Internet, it is still very common.

The code is simply listed below:

<code><span>/** {{{ dcode_png_writer()
 * function is custom png_write callback function
 * Return void */</span><span>static</span><span>void</span> dcode_png_writer(png_structp png_ptr, png_bytep data, png_size_t length)
{
    png_mem_encode* p = (png_mem_encode*) png_get_io_ptr(png_ptr);
    size_t nsize = p->size + length;

    <span>if</span> (p->buffer)
        p->buffer = erealloc(p->buffer, nsize);
    <span>else</span>
        p->buffer = emalloc(nsize);

    <span>if</span> (!p->buffer)
    {
        png_error(png_ptr, <span>"PNG allocate memory error"</span>);
        <span>exit</span>(FAILURE);
    }

    <span>memcpy</span>(p->buffer + p->size, data, length);
    p->size += length;
}
<span>/* }}} */</span></code>
Copy after login
<code><span>/** {{{ dcode_write_to_png()
 * write qrcode struct to memory
 * Return char* */</span><span>static</span><span>char</span>* dcode_write_to_png(QRcode *qrcode, <span>int</span> size, <span>int</span> margin, <span>int</span> *pp_len)
{

    png_structp png_ptr;
    png_infop info_ptr;

    <span>unsigned</span><span>char</span> *row, *p, *q;
    <span>int</span> x, y, xx, yy, bit;
    <span>int</span> realwidth;

    realwidth = (qrcode->width + margin * <span>2</span>) * size;
    <span>int</span> row_fill_len = (realwidth + <span>7</span>) / <span>8</span>;

    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    <span>if</span> (png_ptr == NULL)
    {
        php_error(E_ERROR, <span>"Failed to initialize PNG writer"</span>);
        <span>return</span> NULL;
    }

    info_ptr = png_create_info_struct(png_ptr);
    <span>if</span> (info_ptr == NULL)
    {
        php_error(E_ERROR, <span>"Failed to initialize PNG info"</span>);
        <span>return</span> NULL;
    }

    <span>if</span> (setjmp(png_jmpbuf(png_ptr)))
    {
        png_destroy_write_struct(&png_ptr, &info_ptr);
        php_error(E_ERROR, <span>"Failed to set PNG jmpbuf"</span>);
        <span>return</span> NULL;
    }

    row = (<span>unsigned</span><span>char</span> *) emalloc(row_fill_len);
    <span>if</span> (row == NULL)
    {
        png_destroy_write_struct(&png_ptr, &info_ptr);
        php_error(E_ERROR, <span>"Failed to allocate memory"</span>);
        <span>return</span> NULL;
    }

    png_mem_encode state = {NULL, <span>0</span>};
    png_set_write_fn(png_ptr, &state, &dcode_png_writer, NULL);

    png_set_IHDR(png_ptr,
                info_ptr,
                realwidth,
                realwidth,
                <span>1</span>,
                PNG_COLOR_TYPE_GRAY,
                PNG_INTERLACE_NONE,
                PNG_COMPRESSION_TYPE_DEFAULT,
                PNG_FILTER_TYPE_DEFAULT);

    png_write_info(png_ptr, info_ptr);
    <span>memset</span>(row, <span>0xff</span>, (realwidth + <span>7</span>) / <span>8</span>);
    <span>for</span>(y = <span>0</span>; y < margin * size; y ++) {
        png_write_row(png_ptr, row);
    }

    p = qrcode->data;
    <span>for</span>(y = <span>0</span>; y < qrcode->width; y ++) {
        bit = <span>7</span>;
        <span>memset</span>(row, <span>0xff</span>, (realwidth + <span>7</span>) / <span>8</span>);
        q = row;
        q += margin * size / <span>8</span>;
        bit = <span>7</span> - (margin * size % <span>8</span>);
        <span>for</span>(x = <span>0</span>; x < qrcode->width; x ++) {
            <span>for</span>(xx = <span>0</span>; xx <size; xx ++) {
                *q ^= (*p & <span>1</span>) << bit;
                bit--;
                <span>if</span>(bit < <span>0</span>) {
                    q++;
                    bit = <span>7</span>;
                }
            }
            p++;
        }
        <span>for</span>(yy = <span>0</span>; yy < size; yy ++ ) {
            png_write_row(png_ptr, row);
        }
    }

    <span>memset</span>(row, <span>0xff</span>, (realwidth + <span>7</span>) / <span>8</span>);
    <span>for</span>(y = <span>0</span>; y < margin * size; y ++) {
        png_write_row(png_ptr, row);
    }

    png_write_end(png_ptr, info_ptr);
    png_destroy_write_struct(&png_ptr, &info_ptr);

    efree(row);

    <span>char</span> *bin_data = NULL;
    <span>if</span> (state.buffer) {
        bin_data = estrndup(state.buffer, state.size);
        *pp_len = state.size;
        efree(state.buffer);
    }

    <span>return</span> bin_data;
}
<span>/** }}} */</span></code>
Copy after login
  1. The first function dcode_png_writer is a custom callback function for writing png data.
  2. The second functiondcode_write_to_png is to write QRcode data to png

You can mainly look at this part

<code>png_set_write_fn(png_ptr, &state, &dcode_png_writer, NULL);</code>
Copy after login

This is where the custom write function dcode_png_writer is called to write the data to state In the structure, the state structure is as follows. The

<code><span>typedef</span><span>struct</span> _png_mem_encode {
    <span>char</span> *buffer;
    size_t size;
} png_mem_encode ;</code>
Copy after login

png_set_write_fn function sets a custom write function, and uses dcode_png_writer to write data like state and dynamically allocate memory.

For the definition of png_set_write_fn, you can refer to the PNG document mentioned above. The custom function can also customize functions such as error handling, so that it can take over the error handler according to the actual situation instead of letting it exit internally. For more related codes, please see DCode extension

The speed of generating QRCode is still very fast. If you use for ($i = 0; $i < 10000; $i ++) as a parameter, 10,000 can be generated in 3 seconds.

Copyright Statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.

The above introduces the PHP extension development notes (10) Customize the IO function in the libpng library and write the image into the memory, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to convert PNG to JPG on Windows 11 How to convert PNG to JPG on Windows 11 May 12, 2023 pm 03:55 PM

How to Convert PNG to JPG on Windows 11 On Windows 10 and 11, you can use Microsoft's built-in Paint app to quickly convert image files. To convert a PNG image to JPG on Windows 11, use the following steps: Open File Explorer and navigate to the PNG image you want to convert. Right-click the image and select Open With > Draw from the menu. Your photo or image opens in the Paint app. Note the file size at the bottom of the screen. To convert a file from PNG to JPG, click File and select Save As > JPEG Image from the menu. When the file resource

Use java's File.length() function to get the size of the file Use java's File.length() function to get the size of the file Jul 24, 2023 am 08:36 AM

Use Java's File.length() function to get the size of a file. File size is a very common requirement when dealing with file operations. Java provides a very convenient way to get the size of a file, that is, using the length() method of the File class. . This article will introduce how to use this method to get the size of a file and give corresponding code examples. First, we need to create a File object to represent the file we want to get the size of. Here is how to create a File object: Filef

What is the difference between null and NULL in c language What is the difference between null and NULL in c language Sep 22, 2023 am 11:48 AM

The difference between null and NULL in C language is: null is a macro definition in C language, usually used to represent a null pointer, which can be used to initialize pointer variables, or to determine whether the pointer is null in a conditional statement; NULL is a macro definition in C language A predefined constant in , usually used to represent a null value, used to represent a null pointer, null pointer array or null structure pointer.

What do undefined and null mean? What do undefined and null mean? Nov 20, 2023 pm 02:39 PM

In JavaScript, both undefined and null represent the concept of "nothing": 1. undefined represents an uninitialized variable or a non-existent property. When a variable is declared but no value is assigned to it, the value of the variable is undefined , when accessing properties that do not exist in the object, the returned value is also undefined; 2. null represents an empty object reference. In some cases, the object reference can be set to null to release the memory it occupies.

How to rename the extension of all files within a folder, including subfolders How to rename the extension of all files within a folder, including subfolders Apr 14, 2023 pm 12:22 PM

Suppose you need to rename the extension of a file from one extension to another, say jpg to png. It's easy, of course! But what if you have multiple files whose extensions need to be changed? Or worse, what if these multiple files are also located in multiple folders and subfolders, within a single folder? Well, for a normal person, this can be a nightmare. But for a geek, absolutely not. The question now is, are you a geek? Well, with the help of Geek Page, you definitely are! In this article, we explain how to easily rename the extension of all files within a folder, including subfolders of your choice, from one extension to another through a batch script method. Notice:

When to use null and undefined When to use null and undefined Nov 13, 2023 pm 02:11 PM

Both null and undefined indicate a lack of value or an undefined state. Depending on the usage scenario, there are some guiding principles for choosing to use null or undefined: 1. When you need to clearly indicate that a variable is empty or invalid, you can use null; 2. When a variable has been declared but not yet assigned a value, it will be set to undefined by default; 3. When you need to check whether a variable is empty or undefined, use the strict equality operator "===" to determine whether the variable is null or undefined. .

What is the difference between null and undefined What is the difference between null and undefined Nov 08, 2023 pm 04:43 PM

The difference between null and undefined is: 1. Semantic meaning; 2. Usage scenarios; 3. Comparison with other values; 4. Relationship with global variables; 5. Relationship with function parameters; 6. Nullability check; 7. Performance considerations; 8. Performance in JSON serialization; 9. Relationship with types. Detailed introduction: 1. Semantic meaning, null usually means knowing that this variable will not have any valid object value, while undefined usually means that the variable has not been assigned a value, or the object does not have this attribute; 2. Usage scenarios, etc.

What format is png? What format is png? Dec 10, 2020 pm 04:16 PM

png is a bitmap format that uses a lossless compression algorithm. The PNG format has three forms: 8-bit, 24-bit, and 32-bit. The 8-bit PNG supports two different transparent forms. The 24-bit PNG does not support transparency. The 32-bit PNG adds an 8-bit transparent channel to the 24-bit. Therefore, Can display 256 levels of transparency.

See all articles