search
HomeBackend DevelopmentPHP TutorialPHP extension development notes (10) Customize the IO function in the libpng library to write pictures into memory

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>
<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 data;
    <span>for</span>(y = <span>0</span>; y 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 width; x ++) {
            <span>for</span>(xx = <span>0</span>; xx <size xx>1) if(bit 0) {
                    q++;
                    bit = <span>7</span>;
                }
            }
            p++;
        }
        <span>for</span>(yy = <span>0</span>; yy memset(row, <span>0xff</span>, (realwidth + <span>7</span>) / <span>8</span>);
    <span>for</span>(y = <span>0</span>; y char *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></size></code>
  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>

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>

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 as a parameter, 10,000 can be generated in 3 seconds. <code>

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
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

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 Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

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),