swift调用pngquant批量压缩图片

{% github amosavian FileProvider b597244 width = 30% %}

安装FilesProvider

使用FilesProvider来做文件处理,通过SPM管理库依赖

  1. 配置Package.swift
1
2
3
4
5
6
7
8
9
dependencies: [
    // Dependencies declare other packages that this package depends on.
    // .package(url: /* package url */, from: "1.0.0"), 指定版本。giturl
    .package(path: "/Users/admin/hsg/FileProvider")   //源码clone本地,指定路径
],
    .target(
        name: "SPMCmdLineTool",
        dependencies: ["FilesProvider"]),
]
  1. swift build

单元测试

  1. FilesProvider异步处理:需要XCTestExpectation辅助测试
  2. FilesProvider在处理文件(拷贝/重命名/删除)时,不能使用绝对路径,应采用文件相对于documentsProvider.baseURL的相对路径。否则,在当给定的路径包含root目录时,例如/Users/nam/file.png会提示失败。
  3. 在swift调用shell时,目前只能使用Process.launchedProcess类方法执行shell脚本命令。 有可能在单元测试环境,导致其他两种调用shell的失败。

测通可运行的代码片段

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import FilesProvider
var documentsProvider:LocalFileProvider!
var pngexpectation: XCTestExpectation! = nil
override func setUp() {
    // Put setup code here. This method is called before the invocation of each test method in the class.
    documentsProvider = LocalFileProvider(for: .userDirectory, in: .allDomainsMask)
    pngexpectation = self.expectation(description: "BLDownloadImageNotification")
}

func testExample() {
    // This is an example of a functional test case.
    // Use XCTAssert and related functions to verify your tests produce the correct results.
    //创建文件夹
    documentsProvider.create(folder: "testPng", at: "admin/hsg/") { (err) in
        print("新建目录成功")
        //拷贝图片到目录
        self.documentsProvider.contentsOfDirectory(path: "admin/Desktop",           
            completionHandler: { (contents, error) in
            for file in contents
            {
                let png = file.path.hasSuffix("png")
                if png{
                    print("文件路径:\(file.path)")
                    let thePath:NSString = file.path as NSString
                    let toFile = "admin/hsg/testPng/\(thePath.lastPathComponent)"
                    self.documentsProvider.copyItem(path: file.path, to: toFile, overwrite: true, completionHandler: { (err) in
                        //调用shell工具压缩图片
                        self.testProcessRunShellScript(filePath: toFile)
                        print("Name: \(file.name)")
                        print("Size: \(file.size)")
                        print("路径: \(file.path)")
                    })
                }
            }
        })
    }
    waitForExpectations(timeout: 40, handler: nil)
}
//可用
func testProcessRunShellScript(filePath:String) {
    let sub = "_temp.png"
    let pngquantFile = "/Users/"+filePath
    let tmpFilePath = filePath.replacingOccurrences(of: ".png", with: sub)
    let exePath = "/Users/admin/hsg/hexo/GitSubmodules/hsgTool/pngquant/pngquant"
    Process.launchedProcess(launchPath: exePath, arguments: ["--ext",sub,"--speed=3",pngquantFile])
    // 删除旧文件
//        documentsProvider.removeItem(path: filePath) { (error) in
//            //重命名压缩过的tmp文件
//            print("ddddddderr:\(error?.localizedDescription)")
//            self.documentsProvider.moveItem(path: tmpFilePath, to: filePath, overwrite: true,  completionHandler: { (error) in
//                self.pngexpectation.fulfill()
//            })
//        }
}

使用swift开发自己的命令行工具

{% github it-boyer Panagram_Final 8023350 width = 30% %} Command Line Programs on macOS Tutorial swift编写命令行工具

更新7/21/17:macOS教程上的命令行程序已经更新为Xcode 9和Swift 4。

前言

典型的Mac用户使用图形用户界面(GUI)与计算机交互。gui,顾名思义,是基于用户通过输入设备(如鼠标)与计算机进行视觉交互,通过选择或操作屏幕元素(如菜单、按钮等)。 不久前,在GUI出现之前,命令行接口(CLI)还是与计算机交互的主要方法。CLIs是基于文本的接口,用户可以在其中输入要执行的程序名,后面跟着参数。 尽管gui很流行,命令行程序仍然在当今的计算世界中扮演着重要的角色。命令行程序(如ImageMagickffmpeg)在服务器世界中非常重要。事实上,大多数形成Internet的服务器只运行命令行程序。 甚至Xcode也使用命令行程序!当Xcode构建项目时,它调用xcodebuild,它执行实际的构建。如果构建过程被嵌入到Xcode产品中,持续集成解决方案将很难实现,如果不是不可能的话!

Swift直接调用Python函数库

{% github PerfectlySoft Perfect-Python 63589be width = 30% %}

Perfect - Python

本项目提供了在Swift服务器应用上直接引用Python 2.7函数库的简便方法。

本项目采用Swift Package Manager 软件包管理器编译,是Perfect 项目的一部分,但是也可以独立运行

批量压缩png图片工具

{% github it-boyer width = 30% %}

pngquant

使用pngquant批量压缩png

  1. 编写批量处理脚本 vi compresspng.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

import os
import sys
## 参考https://www.jianshu.com/p/bfa29141437e
# 执行文件路径:
    # os.path.realpath(__file__)
    # sys.argv[0]
# 当前图片目录:os.getcwd()
# 文件目录:sys.path[0]

# 获取终端参数
#   sys.argv[1]
# 用法
# pngTo imgDir 默认目录路径

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)
            extension = os.path.splitext(filepath)[1][1:]
            if needExtFilter and extension == ext in ext:
                allfiles.append(filepath)
    return allfiles

if __name__ == '__main__':
    rootDir=sys.path[0]
    PngquantExe = rootDir + "/pngquant"
    print(len(sys.argv))
    if len(sys.argv) == 1:  #当没有传目录参数时,默认获取当前目录
        srcDir = os.getcwd()
    else:
        srcDir=sys.argv[1]  #获取用户指定的目录路径
    print(srcDir)
    imgFiles=GetFileFromThisRootDir(srcDir, 'png')
    suffix="_temp.png"
    for f in imgFiles:
        cmd = "\"" + PngquantExe + "\"" + " --ext " + suffix + " --force --speed=3 "+ f
        os.system(cmd)
        os.remove(f)
        newfile=f.replace(".png", suffix)
        os.rename(newfile, f)
print("压缩完成")

用法

Zsh插件之github使用

github插件

This plugin supports working with GitHub from the command line. It provides a few things:

  • Sets up the hub wrapper and completions for the git command if you have hub installed.
  • Completion for the github Ruby gem.
  • Convenience functions for working with repos and URLs.

Functions

  • empty_gh - Creates a new empty repo (with a README.md) and pushes it to GitHub
  • new_gh - Initializes an existing directory as a repo and pushes it to GitHub
  • exist_gh - Takes an existing repo and pushes it to GitHub
  • git.io - Shortens a URL using git.io

Android安装BusyBox

大家是否有过这样的经历,在命令行里输入adb shell,然后使用命令操作你的手机或模拟器,但是那些命令都是常见Linux命令的阉割缩水版,用起来很不爽。是否想过在Android上使用较完整的shell呢?用BusyBox吧。不论使用adb连接设备使用命令行还是在手机上直接用terminal emulator都可以。

了解手机处理器ARM

Arm处理器,因为其低功耗和小尺寸而闻名,几乎所有的手机处理器都基于arm,其在嵌入式系统中的应用非常广泛,它的性能在同等功耗产品中也很出色。