imageresizer.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * @fileoverview
  3. * Class Trex.ImageResizer를 포함하고 있다.
  4. *
  5. * @author iamdanielkim
  6. *
  7. */
  8. /**
  9. * img element에 원하는 width, height로 변경된 image를 loading한다.
  10. *
  11. *
  12. * @example
  13. * var imageResizer = new Trex.ImageResizer(el, config);
  14. * imageResizer.execResize(imageurl);
  15. *
  16. * @constructor
  17. * @param {Object} elImage
  18. * @param {Object} config
  19. */
  20. Trex.ImageResizer = Trex.Class.create({
  21. initialize: function(elImage, config) {
  22. var _elImage = elImage;
  23. var _maxWidth = config.maxWidth || 200;
  24. var _maxHeight = config.maxHeight || 200;
  25. var _defImgUrl = config.defImgUrl;
  26. var _loadHandler = config.onComplete || function() {};
  27. function doResize(imgEl, imgurl){
  28. var _resizedHeight, _resizedWidth;
  29. var _originWidth = imgEl.width;
  30. var _originHeight = imgEl.height;
  31. if (_originWidth == _maxWidth && _originHeight == _maxHeight) {
  32. _resizedWidth = _maxWidth;
  33. _resizedHeight = _maxHeight;
  34. } else if (_originWidth < _maxWidth && _originHeight < _maxHeight) {
  35. _resizedWidth = _originWidth;
  36. _resizedHeight = _originHeight;
  37. } else {
  38. _resizedHeight = _maxHeight;
  39. _resizedWidth = Math.floor(_maxHeight * (_originWidth / _originHeight));
  40. if (_resizedWidth > _maxWidth) {
  41. _resizedWidth = _maxWidth;
  42. _resizedHeight = Math.floor(_maxWidth * (_originHeight / _originWidth));
  43. }
  44. }
  45. _elImage.width = _resizedWidth;
  46. _elImage.height = _resizedHeight;
  47. _elImage.src = imgurl;
  48. _loadHandler(_resizedWidth, _resizedHeight);
  49. }
  50. /**
  51. * resize를 실행한다.
  52. *
  53. * @memberOf Trex.ImageResizer.prototype
  54. * @param {Object} imgurl
  55. */
  56. this.execResize = function(imgurl) {
  57. var _tmpImage = new Image();
  58. _tmpImage.onerror = function() {
  59. _elImage.width = _maxWidth;
  60. _elImage.height = _maxHeight;
  61. _elImage.src = _defImgUrl;
  62. _tmpImage = _NULL;
  63. };
  64. if( _tmpImage.onreadystatechange ) { //IE
  65. _tmpImage.onreadystatechange = function() {
  66. if(this.readyState == "complete") {
  67. doResize(_tmpImage, imgurl);
  68. }
  69. };
  70. } else {
  71. _tmpImage.onload = function(){
  72. doResize(_tmpImage, imgurl);
  73. }
  74. }
  75. _tmpImage.src = imgurl;
  76. };
  77. }
  78. });