99 lines
2.6 KiB

  1. /*
  2. * libpipi Proper image processing implementation library
  3. * Copyright (c) 2004-2008 Sam Hocevar <sam@zoy.org>
  4. * All Rights Reserved
  5. *
  6. * $Id$
  7. *
  8. * This library is free software. It comes without any warranty, to
  9. * the extent permitted by applicable law. You can redistribute it
  10. * and/or modify it under the terms of the Do What The Fuck You Want
  11. * To Public License, Version 2, as published by Sam Hocevar. See
  12. * http://sam.zoy.org/wtfpl/COPYING for more details.
  13. */
  14. /*
  15. * pixels.c: pixel-level image manipulation
  16. */
  17. #include "config.h"
  18. #include "common.h"
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <math.h>
  23. #include "pipi.h"
  24. #include "pipi_internals.h"
  25. #define C2I(p) (pow(((double)p)/255., 2.2))
  26. #define I2C(p) ((int)255.999*pow(((double)p), 1./2.2))
  27. /* Return a direct pointer to an image's pixels. */
  28. pipi_pixels_t *pipi_getpixels(pipi_image_t *img, pipi_format_t type)
  29. {
  30. size_t bytes = 0;
  31. int x, y, i;
  32. if(type < 0 || type >= PIPI_PIXELS_MAX)
  33. return NULL;
  34. if(img->last_modified == type)
  35. return &img->p[type];
  36. /* Allocate pixels if necessary */
  37. if(!img->p[type].pixels)
  38. {
  39. switch(type)
  40. {
  41. case PIPI_PIXELS_RGBA32:
  42. bytes = img->w * img->h * 4 * sizeof(uint8_t);
  43. break;
  44. case PIPI_PIXELS_RGBA_F:
  45. bytes = img->w * img->h * 4 * sizeof(float);
  46. break;
  47. default:
  48. return NULL;
  49. }
  50. img->p[type].pixels = malloc(bytes);
  51. }
  52. /* Convert pixels */
  53. if(img->last_modified == PIPI_PIXELS_RGBA32
  54. && type == PIPI_PIXELS_RGBA_F)
  55. {
  56. uint8_t *src = (uint8_t *)img->p[PIPI_PIXELS_RGBA32].pixels;
  57. float *dest = (float *)img->p[type].pixels;
  58. for(y = 0; y < img->h; y++)
  59. for(x = 0; x < img->w; x++)
  60. for(i = 0; i < 4; i++)
  61. dest[4 * (y * img->w + x) + i]
  62. = C2I(src[4 * (y * img->w + x) + i]);
  63. }
  64. else if(img->last_modified == PIPI_PIXELS_RGBA_F
  65. && type == PIPI_PIXELS_RGBA32)
  66. {
  67. float *src = (float *)img->p[PIPI_PIXELS_RGBA_F].pixels;
  68. uint8_t *dest = (uint8_t *)img->p[type].pixels;
  69. for(y = 0; y < img->h; y++)
  70. for(x = 0; x < img->w; x++)
  71. for(i = 0; i < 4; i++)
  72. dest[4 * (y * img->w + x) + i]
  73. = I2C(src[4 * (y * img->w + x) + i]);
  74. }
  75. else
  76. {
  77. memset(img->p[type].pixels, 0, bytes);
  78. }
  79. img->last_modified = type;
  80. return &img->p[type];
  81. }