diff --git a/README-CN.md b/README-CN.md index 2123a18..3747279 100644 --- a/README-CN.md +++ b/README-CN.md @@ -32,6 +32,7 @@ McImage是无侵入式的全量压缩资源图片插件 ### Update Log > v0.0.2以后的用户更新到0.0.2以上需要升级你的mctools文件夹,已经上传到release。 +- 1.5.0 : 更新gradle plugin 到 3.5.0 ,更新获取android资源方式,修复了不支持缩写(assembleDebug 缩写 aD)的问题 - 1.4.0 : 区分优化类型,可选择ConvertWep或Compress, 默认选择Compress. 使用ConvertWep需要min sdk >= 18.但是压缩效果更好 - 1.3.0 : 支持多线程压缩,缩短执行时间 - 1.2.0 : 优先从系统获取压缩命令, 不存在使用本地文件命令 @@ -84,20 +85,19 @@ mctools ```groovy McImageConfig { isCheckSize true //是否检测图片大小,默认为true - optimizeType "ConertWebp" //优化类型,可选"ConvertWebp","Compress",转换为webp或原图压缩,默认Compress,使用ConvertWep需要min sdk >= 18.但是压缩效果更好 + optimizeType "Compress" //优化类型,可选"ConvertWebp","Compress",转换为webp或原图压缩,默认Compress,使用ConvertWep需要min sdk >= 18.但是压缩效果更好 maxSize 1*1024*1024 //大图片阈值,default 1MB enableWhenDebug false //debug下是否可用,default true isCheckPixels true // 是否检测大像素图片,default true - maxWidth 1000 //defualt 1000 如果开启图片宽高检查,默认的最大宽度 - maxHeight 1000 //defualt 1000 如果开启图片宽高检查,默认的最大高度 + maxWidth 1000 //default 1000 如果开启图片宽高检查,默认的最大宽度 + maxHeight 1000 //default 1000 如果开启图片宽高检查,默认的最大高度 whiteList = [ //默认为空,如果添加,对图片不进行任何处理 "icon_launcher.png" ] - mctoolsDir "$rootDir/tools" + mctoolsDir "$rootDir" isSupportAlphaWebp false //是否支持带有透明度的webp,default false,带有透明图的图片会进行压缩 multiThread true //是否开启多线程处理图片,default true - bigImageWhiteList = [ //默认为空,如果添加,大图检测将跳过这些图片 - ] + bigImageWhiteList = [] //默认为空,如果添加,大图检测将跳过这些图片 } ``` diff --git a/README.md b/README.md index bdb551b..413ff6c 100644 --- a/README.md +++ b/README.md @@ -34,15 +34,16 @@ The version 1.0.1 now support all build.gradle version! ### Update Log > The user use v0.0.2 update plugin need update your mctools dir together. -- 1.4.0 : Featrue, Support for selecting different optimization types,"ConvertWebp" or "Compress" can be chosen.Default "Compress". "CompressWebp" is a better compression ratio but it don't support api < 18 -- 1.3.0 : Featrue, Support multi-thread processing +- 1.5.0 : Update gradle plugin to 3.5.0 , change the get android resources way,fix not support abbreviation(such as assembleDebug use aD) bug. +- 1.4.0 : Feature, Support for selecting different optimization types,"ConvertWebp" or "Compress" can be chosen.Default "Compress". "CompressWebp" is a better compression ratio but it don't support api < 18 +- 1.3.0 : Feature, Support multi-thread processing - 1.2.0 : Feature, get compress command from system environment prior to local file - 1.0.1 : Bug fix, fix maxSize float error - 1.0.0 : Support AAPT2 , now don't need to close aapt2 with "android.enableAapt2=false", you can delete this line in gradle.properties. - 0.1.4 : Bug fix, add the white list feature, add the img width and height check feature. - 0.1.2 : Bug fix(Fix the problem that check image size not work) - 0.1.1 : Bug fix(Fix the problem not work for module and fix the problem of enableWhenDebug not work) -- 0.0.4 : Add auto choose system future.Remove webpQualitu config (Set inappropriate will result the img lossless) +- 0.0.4 : Add auto choose system future.Remove webpQuality config (Set inappropriate will result the img lossless) - 0.0.3 : Add webp ! It will auto convert your png (without alpha in min API < 18 and not work in min API < 14) and jpg to webp if it will become more small. - 0.0.2 : Improve the log. @@ -85,20 +86,19 @@ You can set the config in build.gradle.If you not set this,all config will use d ```groovy McImageConfig { isCheckSize true //Whether to detect image size,default true - optimizeType "ConertWebp" //Optimize Type,"ConvertWebp" or "Compress",default "Compress", "CompressWebp" is a better compression ratio but it don't support api < 18 + optimizeType "Compress" //Optimize Type,"ConvertWebp" or "Compress",default "Compress", "CompressWebp" is a better compression ratio but it don't support api < 18 maxSize 1*1024*1024 //big image size threshold,default 1MB - enableWhenDebug false //swithc in debug build,default true + enableWhenDebug false //switch in debug build,default true isCheckPixels true // Whether to detect image pixels of width and height,default true - maxWidth 1000 //defualt 1000 - maxHeight 1000 //defualt 1000 + maxWidth 1000 //default 1000 + maxHeight 1000 //default 1000 whiteList = [ //do not do any optimization for the images who in the list "icon_launcher.png" ] - mctoolsDir "$rootDir/tools" + mctoolsDir "$rootDir" isSupportAlphaWebp false //Whether support convert the Image with Alpha chanel to Webp,default false, the images with alpha chanels will be compressed.if config true, its need api level >=18 or do some compatible measures - multiThread true //Whether open muti-thread processing,default true - bigImageWhiteList = [ //do not detect big size or large pixels for the images who in the list - ] + multiThread true //Whether open multi-thread processing,default true + bigImageWhiteList = [] //do not detect big size or large pixels for the images who in the list } ``` diff --git a/bintray.gradle b/bintray.gradle index 2df0d55..5f2a9a9 100644 --- a/bintray.gradle +++ b/bintray.gradle @@ -4,7 +4,7 @@ apply plugin: 'com.jfrog.bintray' def siteUrl = 'https://github.com/Aweme/McImage' def gitUrl = 'https://github.com/Aweme/McImage.git' group = "com.smallsoho.mobcase" -version = "1.4.0" +version = "1.5.0" Properties properties = new Properties() properties.load(project.rootProject.file('local.properties').newDataInputStream()) diff --git a/publish.gradle b/publish.gradle index 7342cbb..de64585 100644 --- a/publish.gradle +++ b/publish.gradle @@ -1,8 +1,8 @@ apply plugin: 'maven' apply plugin: 'signing' -def DEBUG = true -def VERSION = '1.4.0' +def DEBUG = false +def VERSION = '1.5.0-SNAPSHOT' def GROUP = 'com.smallsoho.mobcase' def ARTIFACT = 'McImage' diff --git a/src/main/java/com/smallsoho/mcplugin/image/ImagePlugin.kt b/src/main/java/com/smallsoho/mcplugin/image/ImagePlugin.kt index 0581257..90af867 100644 --- a/src/main/java/com/smallsoho/mcplugin/image/ImagePlugin.kt +++ b/src/main/java/com/smallsoho/mcplugin/image/ImagePlugin.kt @@ -1,4 +1,4 @@ -package com.smallsoho.mcplugin.image; +package com.smallsoho.mcplugin.image import com.android.build.gradle.AppExtension import com.android.build.gradle.LibraryExtension @@ -11,7 +11,9 @@ import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.Task import java.io.File -import java.util.concurrent.* +import java.util.concurrent.Callable +import java.util.concurrent.Executors +import java.util.concurrent.Future class ImagePlugin : Plugin { @@ -20,11 +22,15 @@ class ImagePlugin : Plugin { private var oldSize: Long = 0 private var newSize: Long = 0 val bigImgList = ArrayList() + + var isDebugTask = false + var isContainAssembleTask = false + override fun apply(project: Project) { mcImageProject = project - //判断是library还是application + //check is library or application val hasAppPlugin = project.plugins.hasPlugin("com.android.application") val variants = if (hasAppPlugin) { (project.property("android") as AppExtension).applicationVariants @@ -36,75 +42,74 @@ class ImagePlugin : Plugin { project.extensions.create("McImageConfig", Config::class.java) mcImageConfig = project.property("McImageConfig") as Config - val taskNames = project.gradle.startParameter.taskNames - var isDebugTask = false - var isContainAssembleTask = false - for (index: Int in 0 until taskNames.size) { - val taskName = taskNames[index] - if (taskName.contains("assemble") || taskName.contains("resguard") || taskName.contains("bundle")) { - if (taskName.toLowerCase().endsWith("debug") && - taskName.toLowerCase().contains("debug")) { - isDebugTask = true + project.gradle.taskGraph.whenReady { + it.allTasks.forEach { task -> + val taskName = task.name + if (taskName.contains("assemble") || taskName.contains("resguard") || taskName.contains("bundle")) { + if (taskName.toLowerCase().endsWith("debug") && + taskName.toLowerCase().contains("debug")) { + isDebugTask = true + } + isContainAssembleTask = true + return@forEach } - isContainAssembleTask = true - break } } - //export build clean - if (!isContainAssembleTask) { - return - } - - project.afterEvaluate { _ -> - + project.afterEvaluate { variants.all { variant -> variant as BaseVariantImpl checkMcTools(project) - //debug enable - if (isDebugTask && !mcImageConfig.enableWhenDebug) { - println("Debug not run !") - return@all - } - - val mergeResourcesTask = project.tasks.findByName("merge${variant.name.capitalize()}Resources") + val mergeResourcesTask = variant.mergeResourcesProvider.get() val mcPicTask = project.task("McImage${variant.name.capitalize()}") - mcPicTask.doLast { _ -> - println("---- McImage Plugin Start ----") - println(mcImageConfig.toString()) + mcPicTask.doLast { + + //debug enable + if (isDebugTask && !mcImageConfig.enableWhenDebug) { + LogUtil.log("Debug not run ^_^") + return@doLast + } - val dir = variant.mergeResources.computeResourceSetList0() //强行调用一下 + //assemble passed + if (!isContainAssembleTask) { + LogUtil.log("Don't contain assemble task, mcimage passed") + return@doLast + } + + LogUtil.log("---- McImage Plugin Start ----") + LogUtil.log(mcImageConfig.toString()) + + val dir = variant.allRawAndroidResources.files val cacheList = ArrayList() val imageFileList = ArrayList() - if (dir != null) { - for (channelDir: File in dir) { - traverseResDir(channelDir, imageFileList, cacheList, object : IBigImage { - override fun onBigImage(file: File) { - bigImgList.add(file.absolutePath) - } - }) - } + for (channelDir: File in dir) { + traverseResDir(channelDir, imageFileList, cacheList, object : IBigImage { + override fun onBigImage(file: File) { + bigImgList.add(file.absolutePath) + } + }) } checkBigImage() val start = System.currentTimeMillis() - mtDispathOptimizeTask(imageFileList) - println(sizeInfo()) - println("---- McImage Plugin End ----, Total Time(ms) : ${System.currentTimeMillis() - start}") + mtDispatchOptimizeTask(imageFileList) + LogUtil.log(sizeInfo()) + LogUtil.log("---- McImage Plugin End ----, Total Time(ms) : ${System.currentTimeMillis() - start}") } + //chmod task val chmodTaskName = "chmod${variant.name.capitalize()}" val chmodTask = project.task(chmodTaskName) - chmodTask.doLast { _ -> + chmodTask.doLast { //chmod if linux if (Tools.isLinux()) { Tools.chmod() @@ -112,12 +117,13 @@ class ImagePlugin : Plugin { } //inject task - (project.tasks.findByName(chmodTask.name) as Task).dependsOn(mergeResourcesTask!!.taskDependencies.getDependencies(mergeResourcesTask)) + (project.tasks.findByName(chmodTask.name) as Task).dependsOn(mergeResourcesTask.taskDependencies.getDependencies(mergeResourcesTask)) (project.tasks.findByName(mcPicTask.name) as Task).dependsOn(project.tasks.findByName(chmodTask.name) as Task) mergeResourcesTask.dependsOn(project.tasks.findByName(mcPicTask.name)) } } + } private fun traverseResDir(file: File, imageFileList: ArrayList, cacheList: ArrayList, iBigImage: IBigImage) { @@ -127,7 +133,7 @@ class ImagePlugin : Plugin { cacheList.add(file.absolutePath) } if (file.isDirectory) { - file.listFiles().forEach { + file.listFiles()?.forEach { if (it.isDirectory) { traverseResDir(it, imageFileList, cacheList, iBigImage) } else { @@ -144,7 +150,7 @@ class ImagePlugin : Plugin { return } if (((mcImageConfig.isCheckSize && ImageUtil.isBigSizeImage(file, mcImageConfig.maxSize)) - || (mcImageConfig.isCheckPixels + || (mcImageConfig.isCheckPixels && ImageUtil.isBigPixelImage(file, mcImageConfig.maxWidth, mcImageConfig.maxHeight))) && !mcImageConfig.bigImageWhiteList.contains(file.name)) { iBigImage.onBigImage(file) @@ -152,8 +158,8 @@ class ImagePlugin : Plugin { imageFileList.add(file) } - private fun mtDispathOptimizeTask(imageFileList: ArrayList) { - if (imageFileList == null || imageFileList.size == 0 || !bigImgList.isEmpty()) { + private fun mtDispatchOptimizeTask(imageFileList: ArrayList) { + if (imageFileList.size == 0 || bigImgList.isNotEmpty()) { return } val coreNum = Runtime.getRuntime().availableProcessors() @@ -184,8 +190,8 @@ class ImagePlugin : Plugin { } private fun optimizeImage(file: File) { - var path: String = file.path - if(File(path).exists()) { + val path: String = file.path + if (File(path).exists()) { oldSize += File(path).length() } when (mcImageConfig.optimizeType) { @@ -198,13 +204,13 @@ class ImagePlugin : Plugin { } private fun countNewSize(path: String) { - if(File(path).exists()) { + if (File(path).exists()) { newSize += File(path).length() } else { //转成了webp val indexOfDot = path.lastIndexOf(".") val webpPath = path.substring(0, indexOfDot) + ".webp" - if(File(webpPath).exists()) { + if (File(webpPath).exists()) { newSize += File(webpPath).length() } else { LogUtil.log("McImage: optimizeImage have some Exception!!!") diff --git a/src/main/java/com/smallsoho/mcplugin/image/utils/CompressUtil.kt b/src/main/java/com/smallsoho/mcplugin/image/utils/CompressUtil.kt index a3a03ee..c5e60c9 100644 --- a/src/main/java/com/smallsoho/mcplugin/image/utils/CompressUtil.kt +++ b/src/main/java/com/smallsoho/mcplugin/image/utils/CompressUtil.kt @@ -10,18 +10,17 @@ class CompressUtil { if (!ImageUtil.isImage(imgFile)) { return } - val oldSize = imgFile.length() - var newSize = 0L + val newSize: Long if (ImageUtil.isJPG(imgFile)) { - var tempFilePath: String = "${imgFile.path.substring(0, imgFile.path.lastIndexOf("."))}_temp" + - "${imgFile.path.substring(imgFile.path.lastIndexOf("."))}" - Tools.cmd("guetzli", "${imgFile.path} ${tempFilePath}") - val tempFile: File = File(tempFilePath) + val tempFilePath: String = "${imgFile.path.substring(0, imgFile.path.lastIndexOf("."))}_temp" + + imgFile.path.substring(imgFile.path.lastIndexOf(".")) + Tools.cmd("guetzli", "${imgFile.path} $tempFilePath") + val tempFile = File(tempFilePath) newSize = tempFile.length() - println("newSize = ${newSize}") + LogUtil.log("newSize = $newSize") if (newSize < oldSize) { - var imgFileName: String = imgFile.path + val imgFileName: String = imgFile.path if (imgFile.exists()) { imgFile.delete() } diff --git a/src/main/java/com/smallsoho/mcplugin/image/utils/HookUtil.kt b/src/main/java/com/smallsoho/mcplugin/image/utils/HookUtil.kt deleted file mode 100644 index 586b3bf..0000000 --- a/src/main/java/com/smallsoho/mcplugin/image/utils/HookUtil.kt +++ /dev/null @@ -1,31 +0,0 @@ -package com.smallsoho.mcplugin.image.utils - -import com.android.build.gradle.tasks.MergeResources -import java.io.File - -fun MergeResources.computeResourceSetList0(): List? { - - val computeResourceSetListMethod = MergeResources::class.java.declaredMethods - .firstOrNull { it.name == "computeResourceSetList" && it.parameterCount == 0 } - ?: return null - - val oldIsAccessible = computeResourceSetListMethod.isAccessible - try { - computeResourceSetListMethod.isAccessible = true - - val resourceSets = computeResourceSetListMethod.invoke(this) as? Iterable<*> - - return resourceSets - ?.mapNotNull { resourceSet -> - val getSourceFiles = resourceSet?.javaClass?.methods?.find { it.name == "getSourceFiles" && it.parameterCount == 0 } - val files = getSourceFiles?.invoke(resourceSet) - @Suppress("UNCHECKED_CAST") - files as? Iterable - } - ?.flatten() - - } finally { - computeResourceSetListMethod.isAccessible = oldIsAccessible - } - -} \ No newline at end of file diff --git a/src/main/java/com/smallsoho/mcplugin/image/utils/ImageUtil.kt b/src/main/java/com/smallsoho/mcplugin/image/utils/ImageUtil.kt index 66eba80..33a700b 100644 --- a/src/main/java/com/smallsoho/mcplugin/image/utils/ImageUtil.kt +++ b/src/main/java/com/smallsoho/mcplugin/image/utils/ImageUtil.kt @@ -1,12 +1,9 @@ package com.smallsoho.mcplugin.image.utils import com.smallsoho.mcplugin.image.Const -import com.sun.org.apache.xpath.internal.operations.Bool - -import javax.imageio.ImageIO -import java.awt.image.BufferedImage import java.io.File import java.io.FileInputStream +import javax.imageio.ImageIO class ImageUtil { diff --git a/src/main/java/com/smallsoho/mcplugin/image/utils/LogUtil.kt b/src/main/java/com/smallsoho/mcplugin/image/utils/LogUtil.kt index 830c726..3acb77c 100644 --- a/src/main/java/com/smallsoho/mcplugin/image/utils/LogUtil.kt +++ b/src/main/java/com/smallsoho/mcplugin/image/utils/LogUtil.kt @@ -1,8 +1,11 @@ package com.smallsoho.mcplugin.image.utils +import java.lang.Exception + class LogUtil { companion object { + fun log(stage: String, filePath: String, oldInfo: String, newInfo: String) { println("[$stage][$filePath][oldInfo: $oldInfo][newInfo: $newInfo]") } @@ -14,6 +17,11 @@ class LogUtil { fun log(str: String) { println(str) } + + fun log(exception: Exception) { + println(exception) + } + } } diff --git a/src/main/java/com/smallsoho/mcplugin/image/utils/MergedUtil.kt b/src/main/java/com/smallsoho/mcplugin/image/utils/MergedUtil.kt deleted file mode 100644 index b77577d..0000000 --- a/src/main/java/com/smallsoho/mcplugin/image/utils/MergedUtil.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.smallsoho.mcplugin.image.utils - -import com.android.build.gradle.tasks.MergeResources -import java.io.File - -class MergedUtil { - companion object { - fun resourcesFileList(): List? { - val computeResourceSetListMethod = MergeResources::class.java.declaredMethods - .firstOrNull { it.name == "computeResourceSetList" && it.parameterCount == 0 } ?: return null - - val oldIsAccessible = computeResourceSetListMethod.isAccessible - try { - computeResourceSetListMethod.isAccessible = true - - val resourceSets = computeResourceSetListMethod.invoke(this) as? Iterable<*> - - return resourceSets - ?.mapNotNull { resourceSet -> - val getSourceFiles = resourceSet?.javaClass?.methods?.find { it.name == "getSourceFiles" && it.parameterCount == 0 } - val files = getSourceFiles?.invoke(resourceSet) - @Suppress("UNCHECKED_CAST") - files as? Iterable - } - ?.flatten() - - } finally { - computeResourceSetListMethod.isAccessible = oldIsAccessible - } - } - } -} \ No newline at end of file diff --git a/src/main/java/com/smallsoho/mcplugin/image/utils/Tools.kt b/src/main/java/com/smallsoho/mcplugin/image/utils/Tools.kt index 9dbf94c..91e5d00 100644 --- a/src/main/java/com/smallsoho/mcplugin/image/utils/Tools.kt +++ b/src/main/java/com/smallsoho/mcplugin/image/utils/Tools.kt @@ -71,7 +71,7 @@ class Tools { return try { bufferReader.readLine() } catch (e: Exception) { - println(e) + LogUtil.log(e) null } } diff --git a/src/main/java/com/smallsoho/mcplugin/image/webp/WebpUtils.kt b/src/main/java/com/smallsoho/mcplugin/image/webp/WebpUtils.kt index 7d189f1..4c72462 100644 --- a/src/main/java/com/smallsoho/mcplugin/image/webp/WebpUtils.kt +++ b/src/main/java/com/smallsoho/mcplugin/image/webp/WebpUtils.kt @@ -10,7 +10,6 @@ class WebpUtils { companion object { private const val VERSION_SUPPORT_WEBP = 14 //api>=14设设备支持webp - private const val VERSION_SUPPORT_TRANSPARENT_WEBP = 18 //api>=18支持透明通道 private const val TAG = "Webp" private fun isPNGConvertSupported(project: Project): Boolean {