Skip to content

Commit

Permalink
Feature: 修改运作机制,将hook函数删除改成标准函数,去掉warning,修复不支持缩写的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
owenlongbo committed Oct 21, 2019
1 parent c11ac4d commit aca2bb6
Show file tree
Hide file tree
Showing 12 changed files with 96 additions and 150 deletions.
12 changes: 6 additions & 6 deletions README-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 : 优先从系统获取压缩命令, 不存在使用本地文件命令
Expand Down Expand Up @@ -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 = [] //默认为空,如果添加,大图检测将跳过这些图片
}
```

Expand Down
22 changes: 11 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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
}
```

Expand Down
2 changes: 1 addition & 1 deletion bintray.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
4 changes: 2 additions & 2 deletions publish.gradle
Original file line number Diff line number Diff line change
@@ -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'

Expand Down
112 changes: 59 additions & 53 deletions src/main/java/com/smallsoho/mcplugin/image/ImagePlugin.kt
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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<Project> {

Expand All @@ -20,11 +22,15 @@ class ImagePlugin : Plugin<Project> {
private var oldSize: Long = 0
private var newSize: Long = 0
val bigImgList = ArrayList<String>()

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
Expand All @@ -36,88 +42,88 @@ class ImagePlugin : Plugin<Project> {
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<String>()

val imageFileList = ArrayList<File>()

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()
}
}

//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<File>, cacheList: ArrayList<String>, iBigImage: IBigImage) {
Expand All @@ -127,7 +133,7 @@ class ImagePlugin : Plugin<Project> {
cacheList.add(file.absolutePath)
}
if (file.isDirectory) {
file.listFiles().forEach {
file.listFiles()?.forEach {
if (it.isDirectory) {
traverseResDir(it, imageFileList, cacheList, iBigImage)
} else {
Expand All @@ -144,16 +150,16 @@ class ImagePlugin : Plugin<Project> {
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)
}
imageFileList.add(file)
}

private fun mtDispathOptimizeTask(imageFileList: ArrayList<File>) {
if (imageFileList == null || imageFileList.size == 0 || !bigImgList.isEmpty()) {
private fun mtDispatchOptimizeTask(imageFileList: ArrayList<File>) {
if (imageFileList.size == 0 || bigImgList.isNotEmpty()) {
return
}
val coreNum = Runtime.getRuntime().availableProcessors()
Expand Down Expand Up @@ -184,8 +190,8 @@ class ImagePlugin : Plugin<Project> {
}

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) {
Expand All @@ -198,13 +204,13 @@ class ImagePlugin : Plugin<Project> {
}

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!!!")
Expand Down
15 changes: 7 additions & 8 deletions src/main/java/com/smallsoho/mcplugin/image/utils/CompressUtil.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down
31 changes: 0 additions & 31 deletions src/main/java/com/smallsoho/mcplugin/image/utils/HookUtil.kt

This file was deleted.

Original file line number Diff line number Diff line change
@@ -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 {

Expand Down
Loading

0 comments on commit aca2bb6

Please sign in to comment.