(RIN forum) updated and safer impl for Local_Storage::load_image_resized() "for those cases where it might fail to allocate memory for the resized image" by RIPAciD: https://cs.rin.ru/forum/viewtopic.php?p=2884627#p2884627

This commit is contained in:
a 2023-08-24 21:03:31 +03:00
parent 4399c0b12b
commit ad9dfb2bd1

View File

@ -793,27 +793,27 @@ std::vector<image_pixel_t> Local_Storage::load_image(std::string const& image_pa
std::string Local_Storage::load_image_resized(std::string const& image_path, std::string const& image_data, int resolution) std::string Local_Storage::load_image_resized(std::string const& image_path, std::string const& image_data, int resolution)
{ {
int width, height; std::string resized_image(resolution * resolution * 4, 0);
char *resized_img = (char *)malloc(sizeof(char) * 184 * 184 * 4); char* resized_img = (char*)malloc(sizeof(char) * resolution * resolution * 4);
unsigned char* img; PRINT_DEBUG("Local_Storage::load_image_resized: %s for resized image (%i)\n", (resized_img == nullptr ? "could not allocate memory" : "memory allocated"), (resolution * resolution * 4));
if (image_path.length() > 0) if (resized_img != nullptr) {
{ if (image_path.length() > 0) {
img = stbi_load(image_path.c_str(), &width, &height, nullptr, 4); int width, height;
unsigned char* img = stbi_load(image_path.c_str(), &width, &height, nullptr, 4);
if (img != nullptr) PRINT_DEBUG("Local_Storage::load_image_resized: \"%s\" %s\n", image_path.c_str(), (img == nullptr ? stbi_failure_reason() : "loaded"));
{ if (img != nullptr) {
stbir_resize_uint8(img, width, height, NULL, (unsigned char *)resized_img, resolution, resolution, NULL, 4); stbir_resize_uint8(img, width, height, NULL, (unsigned char*)resized_img, resolution, resolution, NULL, 4);
stbi_image_free(img); resized_image = std::string(resized_img, resolution * resolution * 4);
stbi_image_free(img);
}
} }
else if (image_data.length() > 0) {
stbir_resize_uint8((unsigned char*)image_data.c_str(), 184, 184, NULL, (unsigned char*)resized_img, resolution, resolution, NULL, 4);
resized_image = std::string(resized_img, resolution * resolution * 4);
}
free(resized_img);
} }
else if (image_data.length() > 0)
{
stbir_resize_uint8((unsigned char *)image_data.c_str(), 184, 184, NULL, (unsigned char *)resized_img, resolution, resolution, NULL, 4);
}
std::string resized_image(resized_img, resolution * resolution * 4);
free(resized_img);
reset_LastError(); reset_LastError();
return resized_image; return resized_image;