ImageUtils.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import { createElementNS } from '../utils.js';
  2. import { SRGBToLinear } from '../math/ColorManagement.js';
  3. let _canvas;
  4. class ImageUtils {
  5. static getDataURL( image ) {
  6. if ( /^data:/i.test( image.src ) ) {
  7. return image.src;
  8. }
  9. if ( typeof HTMLCanvasElement === 'undefined' ) {
  10. return image.src;
  11. }
  12. let canvas;
  13. if ( image instanceof HTMLCanvasElement ) {
  14. canvas = image;
  15. } else {
  16. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  17. _canvas.width = image.width;
  18. _canvas.height = image.height;
  19. const context = _canvas.getContext( '2d' );
  20. if ( image instanceof ImageData ) {
  21. context.putImageData( image, 0, 0 );
  22. } else {
  23. context.drawImage( image, 0, 0, image.width, image.height );
  24. }
  25. canvas = _canvas;
  26. }
  27. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  28. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  29. return canvas.toDataURL( 'image/jpeg', 0.6 );
  30. } else {
  31. return canvas.toDataURL( 'image/png' );
  32. }
  33. }
  34. static sRGBToLinear( image ) {
  35. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  36. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  37. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  38. const canvas = createElementNS( 'canvas' );
  39. canvas.width = image.width;
  40. canvas.height = image.height;
  41. const context = canvas.getContext( '2d' );
  42. context.drawImage( image, 0, 0, image.width, image.height );
  43. const imageData = context.getImageData( 0, 0, image.width, image.height );
  44. const data = imageData.data;
  45. for ( let i = 0; i < data.length; i ++ ) {
  46. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  47. }
  48. context.putImageData( imageData, 0, 0 );
  49. return canvas;
  50. } else if ( image.data ) {
  51. const data = image.data.slice( 0 );
  52. for ( let i = 0; i < data.length; i ++ ) {
  53. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  54. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  55. } else {
  56. // assuming float
  57. data[ i ] = SRGBToLinear( data[ i ] );
  58. }
  59. }
  60. return {
  61. data: data,
  62. width: image.width,
  63. height: image.height
  64. };
  65. } else {
  66. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  67. return image;
  68. }
  69. }
  70. }
  71. export { ImageUtils };
粤ICP备19079148号