| 1 | /* |
|---|
| 2 | * authimage.c: decode authimage captchas |
|---|
| 3 | * $Id$ |
|---|
| 4 | * |
|---|
| 5 | * Copyright: (c) 2005 Sam Hocevar <sam@zoy.org> |
|---|
| 6 | * This program is free software; you can redistribute it and/or |
|---|
| 7 | * modify it under the terms of the Do What The Fuck You Want To |
|---|
| 8 | * Public License as published by Banlu Kemiyatorn. See |
|---|
| 9 | * http://sam.zoy.org/projects/COPYING.WTFPL for more details. |
|---|
| 10 | */ |
|---|
| 11 | |
|---|
| 12 | #include <stdio.h> |
|---|
| 13 | #include <stdlib.h> |
|---|
| 14 | #include <string.h> |
|---|
| 15 | #include <limits.h> |
|---|
| 16 | #include <math.h> |
|---|
| 17 | |
|---|
| 18 | #include "config.h" |
|---|
| 19 | #include "common.h" |
|---|
| 20 | |
|---|
| 21 | /* Main function */ |
|---|
| 22 | char *decode_authimage(struct image *img) |
|---|
| 23 | { |
|---|
| 24 | static struct font *font = NULL; |
|---|
| 25 | char *result; |
|---|
| 26 | struct image *tmp; |
|---|
| 27 | int x, y, r, g, b, i; |
|---|
| 28 | |
|---|
| 29 | if(!font) |
|---|
| 30 | { |
|---|
| 31 | font = font_load_fixed("font_authimage.png", |
|---|
| 32 | "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); |
|---|
| 33 | if(!font) |
|---|
| 34 | exit(-1); |
|---|
| 35 | } |
|---|
| 36 | |
|---|
| 37 | /* authimage captchas have 6 characters */ |
|---|
| 38 | result = malloc(7 * sizeof(char)); |
|---|
| 39 | memset(result, '\0', 7); |
|---|
| 40 | |
|---|
| 41 | /* double the captcha size for better accuracy in the rotation */ |
|---|
| 42 | tmp = image_dup(img); |
|---|
| 43 | filter_scale(tmp, 2.0); |
|---|
| 44 | getpixel(tmp, 0, 0, &r, &g, &b); |
|---|
| 45 | filter_equalize(tmp, r * 3 / 4); |
|---|
| 46 | filter_smooth(tmp); |
|---|
| 47 | filter_equalize(tmp, 220); |
|---|
| 48 | |
|---|
| 49 | for(i = 0; i < 6; i++) |
|---|
| 50 | { |
|---|
| 51 | int mindiff = INT_MAX, minch = -1, ch; |
|---|
| 52 | for(ch = 0; ch < font->size; ch++) |
|---|
| 53 | { |
|---|
| 54 | int diff = 0; |
|---|
| 55 | for(y = 0; y < 7; y++) |
|---|
| 56 | { |
|---|
| 57 | for(x = 0; x < 5; x++) |
|---|
| 58 | { |
|---|
| 59 | int newx, newy, r2; |
|---|
| 60 | newx = 35.0 + (x + 6 * i) * 218.0 / 34.0 + y * 5.0 / 6.0 + 0.5; |
|---|
| 61 | newy = 33.0 - (x + 6 * i) * 18.0 / 34.0 + y * 42.0 / 6.0 + 0.5; |
|---|
| 62 | getpixel(tmp, newx, newy, &r, &g, &b); |
|---|
| 63 | getpixel(font->img, x + 6 * ch, y, &r2, &g, &b); |
|---|
| 64 | diff += (r - r2) * (r - r2); |
|---|
| 65 | } |
|---|
| 66 | } |
|---|
| 67 | if(diff < mindiff) |
|---|
| 68 | { |
|---|
| 69 | mindiff = diff; |
|---|
| 70 | minch = ch; |
|---|
| 71 | } |
|---|
| 72 | } |
|---|
| 73 | result[i] = font->glyphs[minch].c; |
|---|
| 74 | } |
|---|
| 75 | |
|---|
| 76 | image_free(tmp); |
|---|
| 77 | |
|---|
| 78 | return result; |
|---|
| 79 | } |
|---|
| 80 | |
|---|