imageCompression.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. /**
  2. * 图片压缩工具
  3. * 用于压缩大于1MB的图片到0.8MB-1MB之间,保持原文件格式
  4. */
  5. /**
  6. * 压缩图片到目标大小范围
  7. * @param file - 原始图片文件
  8. * @param targetMinSize - 目标最小大小(字节)
  9. * @param targetMaxSize - 目标最大大小(字节)
  10. * @param quality - 压缩质量(0-1),默认0.9
  11. * @returns Promise<File> - 压缩后的文件
  12. */
  13. async function compressImageToTargetSize(
  14. file: File,
  15. targetMinSize: number,
  16. targetMaxSize: number,
  17. quality: number = 0.9
  18. ): Promise<File> {
  19. return new Promise((resolve, reject) => {
  20. const canvas = document.createElement('canvas')
  21. const ctx = canvas.getContext('2d')
  22. const img = new Image()
  23. img.onload = () => {
  24. try {
  25. const originalWidth = img.width
  26. const originalHeight = img.height
  27. // 先尝试保持原尺寸,只调整质量
  28. canvas.width = originalWidth
  29. canvas.height = originalHeight
  30. if (ctx) {
  31. ctx.imageSmoothingEnabled = true
  32. ctx.imageSmoothingQuality = 'high'
  33. }
  34. // 绘制原始尺寸的图片
  35. ctx?.drawImage(img, 0, 0, originalWidth, originalHeight)
  36. // 转换为blob
  37. canvas.toBlob(
  38. (blob) => {
  39. if (!blob) {
  40. reject(new Error('图片压缩失败'))
  41. return
  42. }
  43. // 检查压缩结果是否在目标范围内
  44. if (blob.size >= targetMinSize && blob.size <= targetMaxSize) {
  45. const compressedFile = new File([blob], file.name, {
  46. type: file.type,
  47. lastModified: Date.now()
  48. })
  49. resolve(compressedFile)
  50. } else if (blob.size > targetMaxSize) {
  51. // 如果还是太大,需要调整尺寸
  52. compressWithSizeAdjustment(file, img, targetMinSize, targetMaxSize, quality, resolve, reject)
  53. } else {
  54. // 如果太小了,提高质量重新压缩
  55. compressWithHigherQuality(file, img, targetMinSize, targetMaxSize, quality, resolve, reject)
  56. }
  57. },
  58. file.type,
  59. quality
  60. )
  61. } catch (error) {
  62. reject(new Error('图片压缩过程中发生错误: ' + error.message))
  63. }
  64. }
  65. img.onerror = () => {
  66. reject(new Error('图片加载失败'))
  67. }
  68. // 创建图片URL
  69. const reader = new FileReader()
  70. reader.onload = (e) => {
  71. img.src = e.target?.result as string
  72. }
  73. reader.onerror = () => {
  74. reject(new Error('文件读取失败'))
  75. }
  76. reader.readAsDataURL(file)
  77. })
  78. }
  79. /**
  80. * 通过调整尺寸进行压缩
  81. */
  82. function compressWithSizeAdjustment(
  83. file: File,
  84. img: HTMLImageElement,
  85. targetMinSize: number,
  86. targetMaxSize: number,
  87. quality: number,
  88. resolve: (file: File) => void,
  89. reject: (error: Error) => void
  90. ) {
  91. const canvas = document.createElement('canvas')
  92. const ctx = canvas.getContext('2d')
  93. const originalWidth = img.width
  94. const originalHeight = img.height
  95. // 计算目标尺寸,使用更保守的缩放策略
  96. const targetSize = (targetMinSize + targetMaxSize) / 2
  97. const sizeRatio = targetSize / file.size
  98. // 使用更温和的缩放比例,避免过度压缩
  99. let scale = Math.sqrt(sizeRatio) * 1.2 // 比理论值稍大一些,避免过度压缩
  100. // 确保缩放比例在合理范围内
  101. scale = Math.max(0.5, Math.min(1.0, scale))
  102. const targetWidth = Math.floor(originalWidth * scale)
  103. const targetHeight = Math.floor(originalHeight * scale)
  104. canvas.width = targetWidth
  105. canvas.height = targetHeight
  106. if (ctx) {
  107. ctx.imageSmoothingEnabled = true
  108. ctx.imageSmoothingQuality = 'high'
  109. }
  110. // 绘制缩放后的图片
  111. ctx?.drawImage(img, 0, 0, targetWidth, targetHeight)
  112. canvas.toBlob(
  113. (blob) => {
  114. if (!blob) {
  115. reject(new Error('图片压缩失败'))
  116. return
  117. }
  118. const compressedFile = new File([blob], file.name, {
  119. type: file.type,
  120. lastModified: Date.now()
  121. })
  122. // 检查结果,如果还是太大,继续调整
  123. if (blob.size > targetMaxSize && scale > 0.5) {
  124. // 递归调用,进一步缩小
  125. const newScale = scale * 0.9
  126. const newWidth = Math.floor(originalWidth * newScale)
  127. const newHeight = Math.floor(originalHeight * newScale)
  128. canvas.width = newWidth
  129. canvas.height = newHeight
  130. ctx?.drawImage(img, 0, 0, newWidth, newHeight)
  131. canvas.toBlob(
  132. (newBlob) => {
  133. if (newBlob) {
  134. const newFile = new File([newBlob], file.name, {
  135. type: file.type,
  136. lastModified: Date.now()
  137. })
  138. resolve(newFile)
  139. } else {
  140. resolve(compressedFile) // 如果二次压缩失败,返回第一次的结果
  141. }
  142. },
  143. file.type,
  144. quality
  145. )
  146. } else {
  147. resolve(compressedFile)
  148. }
  149. },
  150. file.type,
  151. quality
  152. )
  153. }
  154. /**
  155. * 通过提高质量重新压缩(当压缩结果太小时)
  156. */
  157. function compressWithHigherQuality(
  158. file: File,
  159. img: HTMLImageElement,
  160. targetMinSize: number,
  161. targetMaxSize: number,
  162. currentQuality: number,
  163. resolve: (file: File) => void,
  164. reject: (error: Error) => void
  165. ) {
  166. const canvas = document.createElement('canvas')
  167. const ctx = canvas.getContext('2d')
  168. canvas.width = img.width
  169. canvas.height = img.height
  170. if (ctx) {
  171. ctx.imageSmoothingEnabled = true
  172. ctx.imageSmoothingQuality = 'high'
  173. }
  174. // 提高质量,但不超过0.95
  175. const newQuality = Math.min(0.95, currentQuality + 0.1)
  176. ctx?.drawImage(img, 0, 0, img.width, img.height)
  177. canvas.toBlob(
  178. (blob) => {
  179. if (!blob) {
  180. reject(new Error('图片压缩失败'))
  181. return
  182. }
  183. const compressedFile = new File([blob], file.name, {
  184. type: file.type,
  185. lastModified: Date.now()
  186. })
  187. // 如果提高质量后仍然太小,或者已经达到最高质量,直接返回
  188. if (blob.size < targetMinSize && newQuality < 0.95) {
  189. compressWithHigherQuality(file, img, targetMinSize, targetMaxSize, newQuality, resolve, reject)
  190. } else {
  191. resolve(compressedFile)
  192. }
  193. },
  194. file.type,
  195. newQuality
  196. )
  197. }
  198. /**
  199. * 压缩图片
  200. * @param file - 原始图片文件
  201. * @param maxSize - 最大文件大小(字节),默认1MB
  202. * @param quality - 压缩质量(0-1),默认0.9
  203. * @returns Promise<File> - 压缩后的文件
  204. */
  205. export async function compressImage(
  206. file: File,
  207. maxSize: number = 1 * 1024 * 1024,
  208. quality: number = 0.9
  209. ): Promise<File> {
  210. // 如果文件小于等于最大限制,直接返回原文件
  211. if (file.size <= maxSize) {
  212. return file
  213. }
  214. // 对于大于1MB的文件,设置目标大小为0.8MB-1MB之间
  215. const targetMinSize = 800 * 1024 // 800KB
  216. const targetMaxSize = maxSize // 1MB
  217. return compressImageToTargetSize(file, targetMinSize, targetMaxSize, quality)
  218. }
  219. /**
  220. * 批量压缩图片
  221. * @param files - 图片文件数组
  222. * @param maxSize - 最大文件大小(字节),默认1MB
  223. * @param quality - 压缩质量(0-1),默认0.8
  224. * @returns Promise<File[]> - 压缩后的文件数组
  225. */
  226. export async function compressImages(
  227. files: File[],
  228. maxSize: number = 1 * 1024 * 1024,
  229. quality: number = 0.8
  230. ): Promise<File[]> {
  231. const results: File[] = []
  232. for (const file of files) {
  233. try {
  234. const compressedFile = await compressImage(file, maxSize, quality)
  235. results.push(compressedFile)
  236. } catch (error) {
  237. console.error(`压缩文件 ${file.name} 失败:`, error)
  238. // 压缩失败时保留原文件
  239. results.push(file)
  240. }
  241. }
  242. return results
  243. }
  244. /**
  245. * 获取图片信息
  246. * @param file - 图片文件
  247. * @returns Promise<{width: number, height: number, size: number, type: string}>
  248. */
  249. export function getImageInfo(file: File): Promise<{
  250. width: number
  251. height: number
  252. size: number
  253. type: string
  254. }> {
  255. return new Promise((resolve, reject) => {
  256. const img = new Image()
  257. img.onload = () => {
  258. resolve({
  259. width: img.width,
  260. height: img.height,
  261. size: file.size,
  262. type: file.type
  263. })
  264. }
  265. img.onerror = () => {
  266. reject(new Error('无法获取图片信息'))
  267. }
  268. const reader = new FileReader()
  269. reader.onload = (e) => {
  270. img.src = e.target?.result as string
  271. }
  272. reader.onerror = () => {
  273. reject(new Error('文件读取失败'))
  274. }
  275. reader.readAsDataURL(file)
  276. })
  277. }