1111#include < node_buffer.h>
1212#include < sys/stat.h>
1313
14+ #include < array>
15+ #include < bit>
16+
1417/* Cairo limit:
1518 * https://lists.cairographics.org/archives/cairo/2010-December/021422.html
1619 */
1720static constexpr int canvas_max_side = (1 << 15 ) - 1 ;
1821
22+ template <std::endian E = std::endian::native>
23+ constexpr auto pixFmt () {
24+ std::array<uint8_t ,5 > fmt{};
25+
26+ if constexpr (E == std::endian::little) {
27+ // Cairo ARGB32 → BGRA bytes
28+ fmt = {2 , 1 , 0 , 3 , 1 };
29+ } else {
30+ // Cairo ARGB32 → ARGB bytes
31+ fmt = {3 , 0 , 1 , 2 , 1 };
32+ }
33+
34+ return fmt;
35+ }
36+
37+
1938#ifdef HAVE_GIF
2039typedef struct {
2140 uint8_t *buf;
@@ -1576,8 +1595,8 @@ cairo_status_t Image::loadBMPFromBuffer(uint8_t *buf, unsigned len){
15761595 BMPParser::Parser parser;
15771596
15781597 // Reversed ARGB32 with pre-multiplied alpha
1579- uint8_t pixFmt[ 5 ] = { 2 , 1 , 0 , 3 , 1 } ;
1580- parser.parse (buf, len, pixFmt );
1598+ auto fmt = pixFmt<>() ;
1599+ parser.parse (buf, len, fmt. data () );
15811600
15821601 if (parser.getStatus () != BMPParser::Status::OK ) {
15831602 errorInfo.reset ();
@@ -1587,20 +1606,30 @@ cairo_status_t Image::loadBMPFromBuffer(uint8_t *buf, unsigned len){
15871606
15881607 width = naturalWidth = parser.getWidth ();
15891608 height = naturalHeight = parser.getHeight ();
1609+ uint32_t src_stride = width * sizeof (uint32_t );
15901610 uint8_t *data = parser.getImgd ();
15911611
1592- _surface = cairo_image_surface_create_for_data (
1593- data,
1612+ int dst_stride = cairo_format_stride_for_width ( CAIRO_FORMAT_ARGB32 , width);
1613+ _surface = cairo_image_surface_create (
15941614 CAIRO_FORMAT_ARGB32 ,
15951615 width,
1596- height,
1597- cairo_format_stride_for_width (CAIRO_FORMAT_ARGB32 , width)
1616+ height
15981617 );
15991618
16001619 // No need to delete the data
16011620 cairo_status_t status = cairo_surface_status (_surface);
16021621 if (status) return status;
16031622
1623+ uint8_t *dst = cairo_image_surface_get_data (_surface);
1624+ for (int y = 0 ; y < height; y++) {
1625+ memcpy (
1626+ dst + y * dst_stride,
1627+ data + y * src_stride,
1628+ src_stride
1629+ );
1630+ }
1631+
1632+ cairo_surface_mark_dirty (_surface);
16041633 _data = data;
16051634 parser.clearImgd ();
16061635
0 commit comments