diff --git a/src/rtextures.c b/src/rtextures.c index 61e528d47..afc69f166 100644 --- a/src/rtextures.c +++ b/src/rtextures.c @@ -1230,23 +1230,31 @@ Image ImageFromImage(Image image, Rectangle rec) { Image result = { 0 }; + // Security check to avoid program crash + if ((image.data == NULL) || (image.width == 0) || (image.height == 0)) return result; + // Basic rectangle validation: size smaller than image size if ((rec.x >= 0) && (rec.y >= 0) && (rec.width > 0) && (rec.height > 0) && (((int)rec.x + (int)rec.width) <= image.width) && (((int)rec.y + (int)rec.height) <= image.height)) { - int bytesPerPixel = GetPixelDataSize(1, 1, image.format); - result.width = (int)rec.width; - result.height = (int)rec.height; - result.data = RL_CALLOC((int)rec.width*(int)rec.height*bytesPerPixel, 1); - result.format = image.format; - result.mipmaps = 1; + if (image.format >= PIXELFORMAT_COMPRESSED_DXT1_RGB) TRACELOG(LOG_WARNING, "IMAGE: Image manipulation not supported for compressed formats"); + else + { + int bytesPerPixel = GetPixelDataSize(1, 1, image.format); - for (int y = 0; y < (int)rec.height; y++) - { - memcpy(((unsigned char *)result.data) + y*(int)rec.width*bytesPerPixel, ((unsigned char *)image.data) + ((y + (int)rec.y)*image.width + (int)rec.x)*bytesPerPixel, (int)rec.width*bytesPerPixel); - } + result.width = (int)rec.width; + result.height = (int)rec.height; + result.data = RL_CALLOC((int)rec.width*(int)rec.height*bytesPerPixel, 1); + result.format = image.format; + result.mipmaps = 1; + + for (int y = 0; y < (int)rec.height; y++) + { + memcpy(((unsigned char *)result.data) + y*(int)rec.width*bytesPerPixel, ((unsigned char *)image.data) + ((y + (int)rec.y)*image.width + (int)rec.x)*bytesPerPixel, (int)rec.width*bytesPerPixel); + } + } } else TRACELOG(LOG_WARNING, "IMAGE: Rectangle provided for ImageToImage not valid");