CaptchaService.php 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Service;
  3. class CaptchaService
  4. {
  5. public function generateCode(): string
  6. {
  7. $characters = ['2', '3', '4', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v','x', 'y', 'z'];
  8. $code = '';
  9. $max = count($characters) - 1;
  10. for ($i = 0; $i < 6; $i++) {
  11. $code .= $characters[random_int(0, $max)];
  12. }
  13. return $code;
  14. }
  15. public function generateImage(string $code): string
  16. {
  17. // Create image
  18. $width = 200;
  19. $height = 50;
  20. $image = imagecreatetruecolor($width, $height);
  21. // Colors
  22. $background = imagecolorallocate($image, 255, 255, 255);
  23. $textColor = imagecolorallocate($image, 33, 33, 33);
  24. $noiseColor = imagecolorallocate($image, 123, 123, 123);
  25. // Fill background
  26. imagefilledrectangle($image, 0, 0, $width, $height, $background);
  27. // Add random lines for noise
  28. for ($i = 0; $i < 4; $i++) {
  29. imageline(
  30. $image,
  31. mt_rand(0, $width),
  32. mt_rand(0, $height),
  33. mt_rand(0, $width),
  34. mt_rand(0, $height),
  35. $noiseColor
  36. );
  37. }
  38. // Add dots for noise
  39. for ($i = 0; $i < 100; $i++) {
  40. imagesetpixel(
  41. $image,
  42. mt_rand(0, $width),
  43. mt_rand(0, $height),
  44. $noiseColor
  45. );
  46. }
  47. // Split code into characters and space them out
  48. $chars = str_split($code);
  49. $spacing = 25; // Space between characters
  50. $startX = 30; // Starting X position
  51. foreach ($chars as $i => $char) {
  52. imagestring(
  53. $image,
  54. 5, // font size (1-5)
  55. $startX + ($i * $spacing),
  56. 15, // Y position
  57. $char,
  58. $textColor
  59. );
  60. }
  61. // Output image as base64
  62. ob_start();
  63. imagepng($image);
  64. $imageData = ob_get_clean();
  65. // Clean up
  66. imagedestroy($image);
  67. return 'data:image/png;base64,' . base64_encode($imageData);
  68. }
  69. }