forked from octalmage/robotjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMMBitmap.c
93 lines (76 loc) · 2.38 KB
/
MMBitmap.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include "MMBitmap.h"
#include <assert.h>
#include <string.h>
MMBitmapRef createMMBitmap(uint8_t *buffer,
size_t width,
size_t height,
size_t bytewidth,
uint8_t bitsPerPixel,
uint8_t bytesPerPixel)
{
MMBitmapRef bitmap = malloc(sizeof(MMBitmap));
if (bitmap == NULL) return NULL;
bitmap->imageBuffer = buffer;
bitmap->width = width;
bitmap->height = height;
bitmap->bytewidth = bytewidth;
bitmap->bitsPerPixel = bitsPerPixel;
bitmap->bytesPerPixel = bytesPerPixel;
return bitmap;
}
void destroyMMBitmap(MMBitmapRef bitmap)
{
assert(bitmap != NULL);
if (bitmap->imageBuffer != NULL) {
free(bitmap->imageBuffer);
bitmap->imageBuffer = NULL;
}
free(bitmap);
}
void destroyMMBitmapBuffer(char * bitmapBuffer, void * hint)
{
if (bitmapBuffer != NULL)
{
free(bitmapBuffer);
}
}
MMBitmapRef copyMMBitmap(MMBitmapRef bitmap)
{
uint8_t *copiedBuf = NULL;
assert(bitmap != NULL);
if (bitmap->imageBuffer != NULL) {
const size_t bufsize = bitmap->height * bitmap->bytewidth;
copiedBuf = malloc(bufsize);
if (copiedBuf == NULL) return NULL;
memcpy(copiedBuf, bitmap->imageBuffer, bufsize);
}
return createMMBitmap(copiedBuf,
bitmap->width,
bitmap->height,
bitmap->bytewidth,
bitmap->bitsPerPixel,
bitmap->bytesPerPixel);
}
MMBitmapRef copyMMBitmapFromPortion(MMBitmapRef source, MMRect rect)
{
assert(source != NULL);
if (source->imageBuffer == NULL || !MMBitmapRectInBounds(source, rect)) {
return NULL;
} else {
uint8_t *copiedBuf = NULL;
const size_t bufsize = rect.size.height * source->bytewidth;
const size_t offset = (source->bytewidth * rect.origin.y) +
(rect.origin.x * source->bytesPerPixel);
/* Don't go over the bounds, programmer! */
assert((bufsize + offset) <= (source->bytewidth * source->height));
copiedBuf = malloc(bufsize);
if (copiedBuf == NULL) return NULL;
memcpy(copiedBuf, source->imageBuffer + offset, bufsize);
return createMMBitmap(copiedBuf,
rect.size.width,
rect.size.height,
source->bytewidth,
source->bitsPerPixel,
source->bytesPerPixel);
}
}