First post my toolman project address github.com/Leifzhang/T…

p.

Today, I give you an article that may or may not be of practical help to you. This is the last blow of the year. Today’s topic is to take a look at Python and the shell.

An Android developer should not be obsessed with language. A while ago, Hongyang shared an article about image optimization by others. I did something similar in early 2020 when I was in Hello, but I did it a bit weirder.

This was inspired by my former brother. At that time, I had to complete the development of traditional version of App, and many Chinese characters were written in Java code due to the non-standard code, so the difficulty of internationalization of the whole project was exponentially increased.

At the time, I felt that this requirement was not particularly easy to do. What did my brother secretly do for this demand? \u4e00-\ u9FA5 = u4e00-\ u9FA5 = u4e00-\ u9FA5 = u4e00-\ u9FA5 = u4e00-\ u9FA5 = u4e00-\ u9FA5

Of course, my brother’s command line tools continue to evolve, and I also contributed some spicy chicken code to them, but brother’s ideas are still very inspiring to me. A code that doesn’t have to be tied to your current attributes, and that makes refactoring pain points easier and easier, is best.

The body of the

Let’s talk about the technology selection first, after all, we have to make sure the plan is good, and then we can have a happy development (brag force).

Png compression

PNG image compression, the first thing to think of is Tinypng, but a Tinypng is a website, but he also provides interface call, but call each other interface needs to charge, leaving tears of poverty.

Later, I investigated pngQuant, which can be executed by the command line with a compression ratio of about 70%. In addition, it can provide good support for our project with python. Those interested in understanding image compression can look at another big guy’s previous analysis of PNG image compression comparison analysis.

Confirming the solution, we simply call the shell command line directly from Python to process the current file.

Pngquant-f --skip-if-larger --strip --ext=.png --quality 70-70 pngquant-f --skip-if-larger --strip --ext=.png --quality 70-70Copy the code

Basically just execute the above command can complete a PNG image compression, and the compression ratio is currently selected 70.

None Alpha Png to JPG

Jpg has a higher compression ratio than Png, but there is a small disadvantage that it does not support transparent images, so if there are PNGS without Alpha in the project, we can convert them directly to Jpg.

PIL(Python Image Library) is a third party Image processing Library for Python, but it is almost considered the official Image processing Library of Python due to its powerful features and large number of users. Its official home page is :PIL. PIL has a long history and used to support only python2.x. Later,pillow is ported to Python3. Pillow claims to be friendly fork for PIL, which has similar functionality to PIL but supports Python3.

Python’s PIL image library is extremely powerful, but the only annoyance is that the dependencies required to install PIP first are slightly demanding for development.

In fact, this part is the same as after Android obtains Bitmap. After PIL obtains Image, it can also obtain the ARGB pixel of the current Image. We just need to judge according to whether the value of A is greater than 0.

def changeImage(file,outPath) :
	filePath = file
	png = Image.open(filePath).convert('RGBA')
	alpha_index = png.getbands().index('A')
	if alpha_index < 0 :
		bg = Image.new('RGB', size = png.size, color = (255.255.255))
		bg.paste(png,png)
		bg.save(outPath)
		print(outPath)
		return alpha_index
	return alpha_index
Copy the code

This part of the code includes checking the image and saving the Png to JPG. PNG.getbands().index(‘A’) indicates the number of Alpha values in the image.

cwebp

Webp is a new image format launched by Google. Compared with common JPG, PNG and GIF formats, webP has the biggest advantage of higher compression rate, smaller image files and saving storage space and network bandwidth under the same quality. More information you can view the website (need self-provided ladder) : developers.google.com/speed/webp/…

Google officially launched the tool CWebP for other image formats and WebP formats for mutual conversion

Here’s a tip: not all PNG images will become smaller when converted to Webp. Some solid color images will actually become larger when converted to WebP.

So the transformation of WebP pictures in fact as long as the use of Google official scheme on the line. We also use the shell command line.

Cwebp -q 75 {} -o {}. Webp -quietCopy the code

The current compression ratio is 75 and silent compression is performed.

Cli development

The above just introduces the technology selection related, but just have these in fact and you really write out or there is a gap. Let’s straighten out the overall logic and see what the next command tool does.

  1. Gets the current file path, traverses the folder images
  2. Obtain the original file size, at the same time the above image compression operation, temp file, compare the difference before and after, if it becomes large, it will not be processed
  3. Finally, select overwrite the original file and delete temp
  4. Finally output the compression size

By the way, my Python is terrible, so if there’s anything wrong, it won’t work anyway.

Get all files with the specified suffix in the specified path
def GetFileFromThisRootDir(dir, ext=None) :allfiles = [] needExtFilter = (ext ! =None)
    for root, dirs, files in os.walk(dir) :for filespath in files:
            filepath = os.path.join(root, filespath)
            #if not ignorePath.__contains__(filepath):
            #print filepath
            text = os.path.splitext(filepath)[0] [1:]
            isIgnore = 0
            for ignoreText in ignorePath:
                if text.find(ignoreText)>=0:
                    isIgnore+= 1
            if isIgnore > 0:
                continue
            if text.find('9') > =0:
                continue
            extension = os.path.splitext(filepath)[1] [1:]
            fileName = os.path.basename(filepath)
            fileName = fileName.split('. ') [0]
            if needExtFilter and extension in ext:
                print fileName
                if needExtFilter and fileName not in ignoreFileName :
                    allfiles.append(filepath)
    return allfiles
Copy the code

The above code is to get the current folder path, then remove some of the folders we don’t need, and then return the entire file list.

We can then use this list of files for subsequent image compression operations in the three different ways described above.

To optimize the

It looks like py is ready to work, but it relies on a lot of command-line tools, so if your teammates don’t install them, you’ll be dead.

So we’re going to a certain increase in this aspect, in the case of most of the computer is a MAC, we need bosses have the homebrew first, if it doesn’t, then you can see the www.jianshu.com/p/7071c1419… .

checkCmd = "which pngquant"
   result = os.system(checkCmd)
   ifresult ! =0:
       cmd = "brew install pngquant"
Copy the code

Then take pngQuant as an example, we can use the command line which pngQuant to determine whether the current device has the corresponding command line tool installed, if not, help developers to install it. This will not only avoid some cases of not installing, but also optimize our CLI experience.

In addition, we can copy our command line tools to the bin directory, so that you can directly use the tool in the command line, you can refer to the sh install.

In addition, I copied my previous boss’s command line hot chicken UI, the user can input to determine which command is currently used.

export LANG=en_US.UTF-8 INSTALL_PATH=`cd ~; pwd`/.toolman/kit CONFIG_PATH=`cd ~; pwd`/.toolman_config
#Clear the screenThe clear function echo_help () {echo "* * * * * * * * * * * * * * * * * * * * * * * mbull help * * * * * * * * * * * * * * * * * * * * * *" echo "1, [u | update] update Kit" echo "2, [PNG | pngquant] using pngquant PNG format compression" echo "3, [m | monkey] Android monkey test" echo "4, [w | webP] use cwebp In PNG format webP "echo" of 5, | JPG [j] using py for the transformation of the PNG format JPG "echo" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * "} / / Action =$1 if [[-z "$action"]]; Then echo_help read -p 'Action if [[-z "$action"]]; then echo "ERROR: action is not valid."; exit 1; fi fi if [ $action == "update" ]||[ $action == "u" ]; then sh $INSTALL_PATH/bin/kitupdate.sh elif [ $action == "png" ]||[ $action == "pngquant" ]; then sh $INSTALL_PATH/bin/pngquant.sh $2 elif [ $action == "monkey" ]||[ $action == "m" ]; then sh $INSTALL_PATH/bin/monkey.sh $* elif [ $action == "webp" ]||[ $action == "w" ]; then sh $INSTALL_PATH/bin/pngToWebp.sh $* elif [ $action == "jpg" ]||[ $action == "j" ]; then sh $INSTALL_PATH/bin/pngToJpg.sh $* else echo "ERROR: Currently supported actions: " echo_help fiCopy the code

Let’s go into picture speaking mode

Let’s see how the compression works.

TODO

I was going to integrate the scaffolding functionality into my toolman component, but I’ve been too lazy to do anything lately and just shelved it. But there are a lot of interesting project optimizations that python can help us do.

conclusion

In fact, an Android developer can use more tools to assist their own better to complete the optimization of the project, do not need to stick to Java. Might as well try cross boundary once, may have unexpected harvest.