index.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. /**
  2. * FeHelper Image Base64 Tools
  3. */
  4. new Vue({
  5. el: '#pageContainer',
  6. data: {
  7. sizeOri: '暂无数据',
  8. sizeBase: '暂无数据',
  9. previewSrc: '',
  10. resultContent: '',
  11. toolName: {'image': '图片转Base64', 'base64': 'Base64转图片'},
  12. curType: 'image',
  13. nextType: 'base64',
  14. txtBase64Input: '',
  15. txtBase64Output: '',
  16. error:''
  17. },
  18. watch: {
  19. txtBase64Input:{
  20. immediate: true,
  21. handler(newVal, oldVal) {
  22. this.error = ''
  23. this.txtBase64Output = ''
  24. if(newVal.length === 0) return
  25. if(newVal.indexOf("data:") === -1) {
  26. this.txtBase64Output = "data:image/jpeg;base64,"+newVal
  27. } else {
  28. this.txtBase64Output = newVal
  29. }
  30. },
  31. }
  32. },
  33. mounted: function () {
  34. // 在tab创建或者更新时候,监听事件,看看是否有参数传递过来
  35. if (location.protocol === 'chrome-extension:') {
  36. chrome.tabs.query({currentWindow: true,active: true, }, (tabs) => {
  37. let activeTab = tabs.filter(tab => tab.active)[0];
  38. chrome.runtime.sendMessage({
  39. type: 'fh-dynamic-any-thing',
  40. thing: 'request-page-content',
  41. tabId: activeTab.id
  42. }).then(resp => {
  43. if(!resp || !resp.content) return ;
  44. if (this.curType !== 'image') {
  45. this.trans();
  46. }
  47. this.convertOnline(resp.content, flag => {
  48. if (!flag) {
  49. alert('抱歉,' + resp.content + ' 对应的图片未转码成功!');
  50. }
  51. });
  52. });
  53. });
  54. }
  55. //监听paste事件
  56. document.addEventListener('paste', (event) => {
  57. if (this.curType !== 'image') return;
  58. this.paste(event);
  59. }, false);
  60. // 监听拖拽
  61. document.addEventListener('drop', (event) => {
  62. event.preventDefault();
  63. event.stopPropagation();
  64. if (this.curType !== 'image') return;
  65. let files = event.dataTransfer.files;
  66. if (files.length) {
  67. if (/image\//.test(files[0].type)) {
  68. this._getDataUri(files[0]);
  69. } else {
  70. alert('请选择图片文件!');
  71. }
  72. }
  73. }, false);
  74. document.addEventListener('dragover', (event) => {
  75. if (this.curType !== 'image') return;
  76. event.preventDefault();
  77. event.stopPropagation();
  78. }, false);
  79. this.loadPatchHotfix();
  80. },
  81. methods: {
  82. loadPatchHotfix() {
  83. // 页面加载时自动获取并注入页面的补丁
  84. chrome.runtime.sendMessage({
  85. type: 'fh-dynamic-any-thing',
  86. thing: 'fh-get-tool-patch',
  87. toolName: 'image-base64'
  88. }, patch => {
  89. if (patch) {
  90. if (patch.css) {
  91. const style = document.createElement('style');
  92. style.textContent = patch.css;
  93. document.head.appendChild(style);
  94. }
  95. if (patch.js && typeof patch.js === 'string' && patch.js.length < 50000) {
  96. try {
  97. new Function(patch.js)();
  98. } catch (e) {
  99. console.error('image-base64补丁JS执行失败', e);
  100. }
  101. }
  102. }
  103. });
  104. },
  105. openOptionsPage(event) {
  106. event.preventDefault();
  107. event.stopPropagation();
  108. chrome.runtime.openOptionsPage();
  109. },
  110. _sizeFormat: function (num) {
  111. if (isNaN(num)) {
  112. return '暂无数据';
  113. }
  114. num = +num;
  115. if (num < 1024) {
  116. return num + ' B';
  117. } else if (num < 1024 * 1024) {
  118. return (num / 1024).toFixed(2) + ' KB';
  119. } else {
  120. return (num / 1024 / 1024).toFixed(2) + ' MB';
  121. }
  122. },
  123. _getDataUri: function (file) {
  124. let reader = new FileReader();
  125. reader.onload = (evt) => {
  126. this.resultContent = evt.target.result;
  127. this.previewSrc = evt.target.result;
  128. this.$refs.panelBox.style.backgroundImage = 'none';
  129. this.sizeOri = this._sizeFormat(file.size);
  130. this.sizeBase = this._sizeFormat(evt.target.result.length);
  131. };
  132. reader.readAsDataURL(file);
  133. },
  134. convertOnline: function (onlineSrc, callback) {
  135. let that = this;
  136. that.previewSrc = onlineSrc;
  137. let image = new Image();
  138. image.src = onlineSrc;
  139. image.onload = function () {
  140. let width = this.naturalWidth;
  141. let height = this.naturalHeight;
  142. // url方式解码失败,再转换成data uri后继续解码
  143. (function createCanvasContext(img, t, l, w, h) {
  144. let canvas = document.createElement('canvas');
  145. canvas.setAttribute('id', 'qr-canvas');
  146. canvas.height = h + 100;
  147. canvas.width = w + 100;
  148. let context = canvas.getContext('2d');
  149. context.fillStyle = 'rgb(255,255,255)';
  150. context.fillRect(0, 0, canvas.width, canvas.height);
  151. context.drawImage(img, l, t, w, h, 50, 50, w, h);
  152. that.resultContent = canvas.toDataURL();
  153. that.$refs.panelBox.style.backgroundImage = 'none';
  154. that.sizeOri = width + 'x' + height;
  155. that.sizeBase = that._sizeFormat(that.resultContent.length);
  156. callback && callback(true);
  157. })(image, 0, 0, width, height);
  158. };
  159. image.onerror = function () {
  160. callback && callback(false);
  161. };
  162. },
  163. convert: function () {
  164. if (this.$refs.fileBox.files.length) {
  165. this._getDataUri(this.$refs.fileBox.files[0]);
  166. this.$refs.fileBox.value = '';
  167. }
  168. },
  169. select: function () {
  170. this.$refs.resultBox.select();
  171. },
  172. upload: function (evt) {
  173. evt.preventDefault();
  174. this.$refs.fileBox.click();
  175. },
  176. paste: function (event) {
  177. let items = event.clipboardData.items || {};
  178. // 优先处理图片
  179. for (let index in items) {
  180. let item = items[index];
  181. if (/image\//.test(item.type)) {
  182. let file = item.getAsFile();
  183. return this._getDataUri(file);
  184. }
  185. }
  186. // 然后处理url
  187. try {
  188. // 逐个遍历
  189. (async () => {
  190. for (let index in items) {
  191. let item = items[index];
  192. if (/text\/plain/.test(item.type)) {
  193. let url = await new Promise(resolve => {
  194. item.getAsString(url => resolve(url))
  195. });
  196. let flag = await new Promise(resolve => {
  197. this.convertOnline(url, flag => resolve(flag));
  198. });
  199. if (flag) break;
  200. }
  201. }
  202. })();
  203. } catch (ex) {
  204. // 只能处理一个了
  205. for (let index in items) {
  206. let item = items[index];
  207. if (/text\/plain/.test(item.type)) {
  208. return item.getAsString(url => {
  209. this.convertOnline(url);
  210. });
  211. }
  212. }
  213. }
  214. },
  215. trans: function () {
  216. this.curType = {image: 'base64', base64: 'image'}[this.curType];
  217. this.nextType = {image: 'base64', base64: 'image'}[this.nextType];
  218. },
  219. loadError: function (e) {
  220. if (this.curType === 'base64' && this.txtBase64Input.trim().length) {
  221. this.error = ('无法识别的Base64编码,请确认是正确的图片Data URI?');
  222. }
  223. },
  224. // 打开打赏页面
  225. openDonateModal: function(event){
  226. event.preventDefault();
  227. event.stopPropagation();
  228. chrome.runtime.sendMessage({
  229. type: 'fh-dynamic-any-thing',
  230. thing: 'open-donate-modal',
  231. params: { toolName: 'image-base64' }
  232. });
  233. },
  234. }
  235. });