How to convert a BMP image to RGB565 with ESP32 (Arduino)

I am currently working on a project involving an ESP32. The ESP32 retrieves a BMP image from a PHP page that converts a JPG to BMP. The ESP32 then needs to convert the BMP image into RGB565 data to be displayed using LVGL. The issue is not with the display or LVGL, as standard images are displayed correctly. However, when the converted image is displayed, it is recognizable, but the colored pixels appear to be randomly placed. I have included pictures at the end for reference.

I tried the following codes which give me the problem mentionned earlier.

The code of my php page is :

<?php
// Function to make a request to the Mouser API and fetch the image
function fetchAndConvertImage() {
    // API key for accessing the Mouser API
    $apiKey = 'MY_API_KEY';
    
    // URL for making a request to the Mouser API
    $url = 'https://api.mouser.com/api/v1/search/keyword?apiKey=' . $apiKey;
    
    // Data to be sent in the request
    $requestData = array(
        'SearchByKeywordRequest' => array(
            'keyword' => 'Thermistor',
            'records' => 0,
            'startingRecord' => 0,
            'searchOptions' => 'string',
            'searchWithYourSignUpLanguage' => 'en'
        )
    );
    
    // Encode the data in JSON format
    $jsonData = json_encode($requestData);
    
    // Set up the options for the POST request
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-Type: application/json',
            'content' => $jsonData
        )
    );
    
    // Create a context for the request
    $context = stream_context_create($options);
    
    // Make the request to the Mouser API
    $response = file_get_contents($url, false, $context);
    
    // Decode the JSON response
    $responseData = json_decode($response, true);
    
    // Extract the image path from the response
    $imagePath = $responseData['SearchResults']['Parts'][0]['ImagePath'];
    
    // Read the image data from the specified URL
    $imageData = file_get_contents("$imagePath");
    
    // Generate a unique file name
    $fileName = uniqid('image_', true) . '.bmp';
    $filePath = __DIR__ . '/' . $fileName;
    
    // Get image dimensions
    $image = imagecreatefromstring($imageData);
    $width = imagesx($image);
    $height = imagesy($image);
    
    // Calculate row size including padding
    $rowSize = floor(($width * 3 + 3) / 4) * 4; // Each pixel is 3 bytes (RGB), and we need to ensure each row is a multiple of 4 bytes
    
    // BMP header
    $bmpHeader = pack('c', 0x42) . pack('c', 0x4D); // Signature BM
    $bmpHeader .= pack('V', 14 + 40 + ($rowSize * $height)); // File size
    $bmpHeader .= pack('v', 0) . pack('v', 0); // Reserved
    $bmpHeader .= pack('V', 14 + 40); // Data offset
    $bmpHeader .= pack('V', 40); // Header size
    $bmpHeader .= pack('V', $width); // Image width
    $bmpHeader .= pack('V', $height); // Image height
    $bmpHeader .= pack('v', 1); // Number of planes
    $bmpHeader .= pack('v', 24); // Bits per pixel
    $bmpHeader .= pack('V', 0); // Compression (0 = no compression)
    $bmpHeader .= pack('V', 0); // Image size (can be 0 when no compression)
    $bmpHeader .= pack('V', 0); // Horizontal resolution (pixels per meter)
    $bmpHeader .= pack('V', 0); // Vertical resolution (pixels per meter)
    $bmpHeader .= pack('V', 0); // Number of colors in the palette
    $bmpHeader .= pack('V', 0); // Number of important colors
    
    // Convert image data to BMP format
    $bmpData = '';
    for ($y = $height - 1; $y >= 0; --$y) {
        for ($x = 0; $x < $width; ++$x) {
            $rgb = imagecolorat($image, $x, $y);
            $color = imagecolorsforindex($image, $rgb);
            $bmpData .= pack('C', $color['blue']); // Blue
            $bmpData .= pack('C', $color['green']); // Green
            $bmpData .= pack('C', $color['red']); // Red
        }
        // Add padding to ensure row size is a multiple of 4 bytes
        $paddingBytes = $rowSize - ($width * 3);
        $bmpData .= str_repeat(pack('C', 0), $paddingBytes);
    }
    
    // Save BMP file
    file_put_contents($filePath, $bmpHeader . $bmpData);
    
    // Free memory
    imagedestroy($image);
    
    // Return file name
    return $fileName;
}

// Call the function to fetch and convert the image
$imagePath = fetchAndConvertImage();
echo "https://theyoungmaker.ddns.net/opencomponent/$imagePath";
?>

and

The function used to get the bmp and convert it in rgb565 on the ESP32:

bool getImageFromURL(String url) {
  http.begin(url);
  int httpCode = http.GET();

  if (httpCode == HTTP_CODE_OK) {
    WiFiClient* stream = http.getStreamPtr();
    size_t totalLen = http.getSize();
    size_t len = totalLen;

    // Allocate buffer for the image data
    uint8_t* bmp_data = (uint8_t*)malloc(len);
    if (!bmp_data) {
      Serial.println("Failed to allocate memory for image data");
      http.end();
      return false;
    }

    // Read data into buffer
    size_t index = 0;
    while (http.connected() && (len > 0 || len == -1)) {
      size_t size = stream->available();
      if (size) {
        int c = stream->readBytes((char*)(bmp_data + index), size);
        index += c;
        if (len > 0) {
          len -= c;
        }
      }
      delay(1);
    }

    // Parse BMP header
    if (bmp_data[0] != 'B' || bmp_data[1] != 'M') {
      Serial.println("Not a valid BMP file");
      free(bmp_data);
      http.end();
      return false;
    }

    uint32_t dataOffset = *((uint32_t*)(bmp_data + 10));
    uint32_t width = *((uint32_t*)(bmp_data + 18));
    uint32_t height = *((uint32_t*)(bmp_data + 22));
    uint16_t bitsPerPixel = *((uint16_t*)(bmp_data + 28));
    uint32_t compression = *((uint32_t*)(bmp_data + 30));

    if (bitsPerPixel != 24 || compression != 0) {
      Serial.println("Unsupported BMP format");
      free(bmp_data);
      http.end();
      return false;
    }

    // Allocate buffer for the image data in 16-bit format (RGB565)
    size_t imgSize = width * height * 2;
    gui_img_nouveau_projet_png_data = (uint8_t*)malloc(imgSize);
    if (!gui_img_nouveau_projet_png_data) {
      Serial.println("Failed to allocate memory for image data");
      free(bmp_data);
      http.end();
      return false;
    }

    // Convert pixel data to 16-bit (RGB565) format
    uint8_t* src = bmp_data + dataOffset;
    uint16_t* dst = (uint16_t*)gui_img_nouveau_projet_png_data;
    for (int y = 0; y < height; y++) {
      for (int x = 0; x < width; x++) {
        uint8_t b = *src++;
        uint8_t g = *src++;
        uint8_t r = *src++;
        *dst++ = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
      }
      // Skip padding bytes if any
      src += (4 - (width * 3) % 4) % 4;
    }

    // Set image descriptor data
    gui_img_nouveau_projet_png.header.always_zero = 0;
    gui_img_nouveau_projet_png.header.w = width;
    gui_img_nouveau_projet_png.header.h = height;
    gui_img_nouveau_projet_png.data_size = imgSize;
    gui_img_nouveau_projet_png.header.cf = LV_IMG_CF_TRUE_COLOR;
    gui_img_nouveau_projet_png.data = gui_img_nouveau_projet_png_data;

    free(bmp_data);
    http.end();
    return true;
  } else {
    Serial.printf("HTTP GET failed, error: %sn", http.errorToString(httpCode).c_str());
    http.end();
    return false;
  }
}

Does anyone know why this problem occurs? I’m unsure if the issue stems from the conversion from JPG to BMP on the server side or from the conversion from BMP to RGB565 on the ESP32. Any insights or suggestions would be greatly appreciated.

The original image is :

The image displayed on the display :

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật