Home  >  Article  >  Backend Development  >  PHP imitates GD to generate BMP pictures

PHP imitates GD to generate BMP pictures

WBOY
WBOYOriginal
2016-07-25 09:02:101183browse
PHP仿GD生成BMP图片
  1. function imagebmp(&$im, $filename = '', $bit = 8, $compression = 0)
  2. {
  3. if (!in_array($bit, array(1, 4, 8, 16, 24, 32)))
  4. {
  5. $bit = 8;
  6. }
  7. else if ($bit == 32) // todo:32 bit
  8. {
  9. $bit = 24;
  10. }
  11. $bits = pow(2, $bit);
  12. // 调整调色板
  13. imagetruecolortopalette($im, true, $bits);
  14. $width = imagesx($im);
  15. $height = imagesy($im);
  16. $colors_num = imagecolorstotal($im);
  17. if ($bit <= 8)
  18. {
  19. // 颜色索引
  20. $rgb_quad = '';
  21. for ($i = 0; $i < $colors_num; $i ++)
  22. {
  23. $colors = imagecolorsforindex($im, $i);
  24. $rgb_quad .= chr($colors['blue']) . chr($colors['green']) . chr($colors['red']) . "";
  25. }
  26. // 位图数据
  27. $bmp_data = '';
  28. // 非压缩
  29. if ($compression == 0 || $bit < 8)
  30. {
  31. if (!in_array($bit, array(1, 4, 8)))
  32. {
  33. $bit = 8;
  34. }
  35. $compression = 0;
  36. // 每行字节数必须为4的倍数,补齐。
  37. $extra = '';
  38. $padding = 4 - ceil($width / (8 / $bit)) % 4;
  39. if ($padding % 4 != 0)
  40. {
  41. $extra = str_repeat("", $padding);
  42. }
  43. for ($j = $height - 1; $j >= 0; $j --)
  44. {
  45. $i = 0;
  46. while ($i < $width)
  47. {
  48. $bin = 0;
  49. $limit = $width - $i < 8 / $bit ? (8 / $bit - $width + $i) * $bit : 0;
  50. for ($k = 8 - $bit; $k >= $limit; $k -= $bit)
  51. {
  52. $index = imagecolorat($im, $i, $j);
  53. $bin |= $index << $k;
  54. $i ++;
  55. }
  56. $bmp_data .= chr($bin);
  57. }
  58. $bmp_data .= $extra;
  59. }
  60. }
  61. // RLE8 压缩
  62. else if ($compression == 1 && $bit == 8)
  63. {
  64. for ($j = $height - 1; $j >= 0; $j --)
  65. {
  66. $last_index = "
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:A brief summary about PHPNext article:A brief summary about PHP