Code:
#include "captcha.h"
int saveImage(const char *filename, gdImagePtr image)
{
FILE *fd = fopen(filename, "wb");
if(fd == NULL) return -1;
gdImagePng(image, fd);
fclose(fd);
return 0;
}
int checkCircle(gdImagePtr image, int x, int y, int positiveColor, int resultColor)
{
float minRadius = 14.5;
float maxRadius = 15.5;
float radius;
float radiusStep = (maxRadius - minRadius) / 3;
int angle;
int px, py;
int angles[360];
int c;
int error = 0;
int max_x = gdImageSX(image);
int max_y = gdImageSY(image);
for(angle = 0; angle < 360; angle++)
{
angles[angle] = 0;
for(radius = minRadius; radius <= maxRadius; radius += radiusStep)
{
px = x + radius * cos(angle * M_PI / 180.0);
py = y + radius * sin(angle * M_PI / 180.0);
if(px < 0) continue;
else if(py < 0) continue;
else if(px >= max_x) continue;
else if(py >= max_y) continue;
c = gdImageGetPixel(image, px, py);
if(c == positiveColor) angles[angle]++;
}
if(angles[angle] == 0) error++;
if(error > 100) return -1;
}
if(error > 70)
{
gdImageSetPixel(image, x, y, resultColor);
//printf(" Solution: %i:%i %i\n", x, y, resultColor);
return 0;
}
return -1;
}
int scanImage(gdImagePtr image, int *px, int *py)
{
int max_x = gdImageSX(image) - 15;
int max_y = gdImageSY(image) - 15;
int x, y;
int white = gdImageColorResolve(image, 255, 255, 255);
int green = gdImageColorResolve(image, 0, 255, 0);
for(x = 15; x < max_x; x++)
{
for(y = 15; y < max_y; y++)
{
if(checkCircle(image, x, y, white, green) == 0)
{
*px = x;
*py = y;
return 0;
}
}
}
return 1;
}
int cleanImage(const char *filename, gdImagePtr *imagePtr)
{
gdImagePtr image = NULL, cleanImage = NULL;
FILE *fd;
int black, white, green;
int c, r, g, b;
int x, y;
fd = fopen(filename, "rb");
if(fd == NULL) return -1;
image = gdImageCreateFromJpeg(fd);
fclose(fd);
if(image == NULL) return -2;
cleanImage = gdImageCreate(gdImageSX(image), gdImageSY(image));
if(cleanImage == NULL)
{
gdImageDestroy(image);
return -3;
}
white = gdImageColorAllocate(cleanImage, 255, 255, 255);
black = gdImageColorAllocate(cleanImage, 0, 0, 0);
green = gdImageColorAllocate(cleanImage, 0, 255, 0);
gdImageFilledRectangle(cleanImage, 0, 0, gdImageSX(cleanImage) - 1, gdImageSY(cleanImage) - 1, black);
for(x = 0; x < gdImageSX(image); x++)
{
for(y = 0; y < gdImageSY(image); y++)
{
c = gdImageGetPixel(image, x, y);
r = gdImageRed(image, c);
g = gdImageGreen(image, c);
b = gdImageBlue(image, c);
if(r >= 200 && g >= 200 && b >= 200)
{
gdImageSetPixel(cleanImage, x, y, white);
}
}
}
gdImageDestroy(image);
*imagePtr = cleanImage;
return 0;
}
int captcha_break(const char *filename, int *x, int *y)
{
gdImagePtr image;
int rc = cleanImage(filename, &image);
if(rc == -1) return -2;
else if(rc == -2) return -3;
else if(rc == -3) return -4;
*x = 0;
*y = 0;
rc = scanImage(image, x, y);
//saveImage("captcha.png", image);
gdImageDestroy(image);
if(rc) return -1;
return 0;
}
Lesezeichen