Image and Pixel Operations
Image & Pixel Operations in graphics.h
This page gives a simple function-by-function overview of pixel and image APIs in graphics.h. Each function has a small snippet, and one full runnable program is provided at the end.
On This Page
putpixel()
Sets the color of one pixel at coordinate (x, y).
void putpixel(int x, int y, int color); putpixel(100, 80, WHITE);
getpixel()
Reads the current color index at coordinate (x, y).
int c = getpixel(100, 80);
if (c == WHITE) {
putpixel(100, 80, RED);
}
imagesize()
Returns the number of bytes needed to store an image block from a rectangle.
unsigned size = imagesize(80, 80, 180, 160);
getimage()
Captures pixels from a rectangular area into a memory buffer.
void *buf = malloc(imagesize(80, 80, 180, 160)); getimage(80, 80, 180, 160, buf);
putimage()
Draws a previously captured image buffer at a new location.
putimage(260, 120, buf, COPY_PUT);
Full Program
This complete example uses all functions together: draw pixels, read a pixel, capture a block, and place it elsewhere.
#include <graphics.h>
#include <conio.h>
#include <stdlib.h>
int main() {
int gd = DETECT, gm;
int i, c;
unsigned size;
void *buf;
initgraph(&gd, &gm, "");
// putpixel(): draw a small diagonal
for (i = 0; i < 80; i++) {
putpixel(80 + i, 70 + i / 2, WHITE);
}
// getpixel(): read one point
c = getpixel(100, 80);
if (c == WHITE) {
outtextxy(20, 20, "Pixel at (100,80) is WHITE");
}
// draw a shape we will capture
setcolor(YELLOW);
rectangle(80, 120, 200, 220);
setfillstyle(SOLID_FILL, LIGHTBLUE);
bar(100, 140, 180, 200);
// imagesize() + getimage()
size = imagesize(80, 120, 200, 220);
buf = malloc(size);
if (buf == NULL) {
closegraph();
return 1;
}
getimage(80, 120, 200, 220, buf);
// putimage(): place captured block at new location
putimage(280, 140, buf, COPY_PUT);
free(buf);
getch();
closegraph();
return 0;
}