美文网首页ios专题
swift-使用Cordova自定义选择图片并压缩插件

swift-使用Cordova自定义选择图片并压缩插件

作者: YHWXQ简简单单的生活 | 来源:发表于2016-08-06 15:41 被阅读995次

下面自定义一个选择图片并进行压缩并且选择图片放大的插件。

1. 样例效果图

点击选择照片按钮,我们可以调用插件里对应的方法来计算。

Simulator Screen Shot 2016年8月6日 下午2.53.34.png Simulator Screen Shot 2016年8月6日 下午3.00.10.png Simulator Screen Shot 2016年8月6日 下午2.53.59.png
2.自定义插件的创建

我们随便在本地建立一个文件夹(比如叫select-image-plugin),在里面放置插件的相关功能实现代码和配置文件。目录结构如下:

Paste_Image.png
下面分别介绍各个文件的内容和功能
(1)src文件夹这个下面就是放置插件的功能实现代码了,可以看到目前 src 文件夹下只有一个 ios 子文件夹。因为本文只实现了 iOS 版的插件,如果还有 Android 版的插件,那么可以在 src 文件夹下再创建个 android 文件夹,然后把相关的 java 代码放到里面。由于功能比较简单,在 ios 文件夹下只有一个实现类 SelectImagePlugin.swift,具体代码如下:
import Foundation

let cachesPath: String = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).last!

@objc(SIPSelectImagePlugin) class SelectImagePlugin : CDVPlugin {
    // 通过时间的方式将图片保存到起来
    func getFullPath() -> String {
        let date = NSDate()
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd-HH-mm-ss-SSS"
        return cachesPath + "/tempImages/image" + formatter.stringFromDate(date) + ".jpg"
    }
  // id表示返回的结果
    var id = ""
    lazy var pickVC: UIImagePickerController = {
        let pickVC = UIImagePickerController()
        pickVC.delegate = self
        pickVC.allowsEditing = true
        return pickVC
    }()
    
    // API 清空图片缓存
    func clearImageCache(command:CDVInvokedUrlCommand) {
        id = command.callbackId
        //返回结果
        var pluginResult:CDVPluginResult?
        pluginResult = CDVPluginResult(status:CDVCommandStatus_OK)
        do {
            print(cachesPath + "/tempImages/")
            try NSFileManager.defaultManager().removeItemAtPath(cachesPath + "/tempImages/")
        }
        catch _ {
            pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "清空图片失败")
        }
        viewController.dismissViewControllerAnimated(true, completion: nil)
        //发送结果
        self.commandDelegate.sendPluginResult(pluginResult, callbackId: self.id)
    }
    
    // API 选择图片
    func selectImage(command:CDVInvokedUrlCommand)
    {
        id = command.callbackId
        let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
        let cancelAction = UIAlertAction(title: "取消", style: .Cancel, handler: nil)
        let photoAction = UIAlertAction(title: "拍照", style: .Default) { (_) in
            self.openCamera()
        }
        let albumAction = UIAlertAction(title: "从相册中选择", style: .Default) { (_) in
            self.openUserPhotoLibrary()
        }
        alertController.addAction(cancelAction)
        alertController.addAction(photoAction)
        alertController.addAction(albumAction)
        self.viewController.presentViewController(alertController, animated: true, completion: nil)
    }
    
    func selectImageResult(array: [String]) {
        //返回结果
        var pluginResult:CDVPluginResult?
        
        if array.isEmpty {
            pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "选择图片失败")
        } else {
            pluginResult = CDVPluginResult(status:CDVCommandStatus_OK, messageAsArray: array)
        }
        viewController.dismissViewControllerAnimated(true, completion: nil)
        //发送结果
        self.commandDelegate.sendPluginResult(pluginResult, callbackId: self.id)
    }
}

/// MARK: 摄像机和相册的操作和代理方法
extension SelectImagePlugin: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    /// 打开照相功能
    private func openCamera() {
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            pickVC.sourceType = .Camera
            self.viewController.presentViewController(pickVC, animated: true, completion: nil)
        } else {
            print("模拟器没有摄像头,请链接真机调试")
        }
    }
    
    /// 打开相册
    private func openUserPhotoLibrary() {
        pickVC.sourceType = .PhotoLibrary
        pickVC.allowsEditing = true
        self.viewController.presentViewController(pickVC, animated: true, completion: nil)
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        print(info)
        // 对用户选着的图片进行质量压缩,上传服务器,本地持久化存储
        if let typeStr = info[UIImagePickerControllerMediaType] as? String {
            if typeStr == "public.image" { 
                if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
                    var data = [NSData]()
                    let smallImage = image
                    data.append(UIImageJPEGRepresentation(smallImage, 0.4)!)
                    for (index, _) in data.enumerate(){
                        print("compressed", index, ":", data[index].length / 1024, "KB")
                    }
                    var path = [String]()
                    for (_, item) in data.enumerate() {
                        do {
                            try NSFileManager.defaultManager().createDirectoryAtPath(cachesPath + "/tempImages", withIntermediateDirectories: true, attributes: nil)
                        } catch _ {
                        }
                        let fullpath = getFullPath()
                        NSFileManager.defaultManager().createFileAtPath(fullpath, contents: item, attributes: nil)
                        print(fullpath)
                        path.append(fullpath)
                    }
                    selectImageResult(path)
                }
            }
        } else {
            print("图片无法获取")
        }
    }
}

(2)select-image-plugin.jsJS模块文件,这里封装了插件的调用方法。我们直接使用 插件名称.插件方法() 即可,这样使用起来更加方便,代码也更加清晰。
注意:定义多个方法时相互间的逗号不要忘记了,最后一个方法不需要添加逗号,否则插件方法无法调用,会报插件不存在错误。
其内容如下:

'use strict';
 
var exec = require('cordova/exec');
var SelectImagePlugin = {
    selectImage: function(onSuccess, onFail) {
        return exec(onSuccess, onFail, 'SelectImagePlugin', 'selectImage', []);
    },

    clearImageCache: function(onSuccess, onFail) {
               if (onSuccess === undefined) {
               onSuccess = function(){};
               }
               if (onFail === undefined) {
               onFail = function(){};
               }
        return exec(onSuccess, onFail, 'SelectImagePlugin', 'clearImageCache', []);
    }
};
module.exports = SelectImagePlugin;

(3)plugin.xml插件的配置文件。用来配置插件的名字,JS模块文件位置,以及各个平台的功能实现源码位置(这里只实现的iOS的功能,所以只配置了iOS平台相关内容)。

<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
    id="select-image-plugin"
    version="0.1">
     
    <name>SelectImagePlugin</name>
    <description>Select image from iOS Camera or Album and return file path</description>
     
    <js-module src="www/select-image-plugin.js">
        <clobbers target="window.SelectImagePlugin" />
    </js-module>
     
    <!-- iOS -->
    <platform name="ios">
        <config-file target="config.xml" parent="/*">
            <feature name="SelectImagePlugin">
                <param name="ios-package" value="SIPSelectImagePlugin" />
            </feature>
        </config-file>
        <source-file src="src/ios/SelectImagePlugin.swift" />
        <!-- 注意:如果iOS项目中还有其他的swift文件或者xib文件,需要按照下面的方法填写,否则会报错
        <source-file src="src/ios/xxx.swift" />
        <resource-file src="src/ios/xxx.xib" />
        -->
    </platform>
</plugin>
3,自定义插件的安装

(1)由于插件是使用 Swift 语言写的,首先在“终端”中进入到项目文件夹,并运行如下命令添加 Swift 支持插件:

cordova plugin add cordova-plugin-add-swift-support

(2)运行如下命令添加这个插件到工程中来:

cordova plugin add 插件所在目录

进入Cordova项目文件夹下的 plugins 文件夹可以看到,自定义插件已经成功的添加进来。当然,这个自定义插件在各个平台工程下也同步安装了。


Paste_Image.png

(3)以后如果想移除这个自定义插件,运行如下命令即可:

cordova plugin remove 插件ID(位于plugin.xml头部)
4,自定义插件的使用 修改首页 index.html 为如下内容。
<!DOCTYPE html>
<html>
    <head>
        <title>口令验证</title>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
            <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
            <script type="text/javascript" charset="utf-8">
            function select() {
                //调用自定义插件
                SelectImagePlugin.selectImage(successFunction, failFunction)
            }
            
            //验证成功
            function successFunction(text){
                // 选择图片并且放大 FullScreenImage这是一个将图片放大的插件
                FullScreenImage.showImageURL("file://" + text);
            }
            
            //验证失败
            function failFunction(message){
                alert("失败:"+message);
            }
            </script>
            <style>
                * {
                    font-size:1em;
                }
            </style>
            </head>
    <body style="padding-top:50px;">
        <input type="text" id="pwd" >
            <button onclick="select();">选择图片</button>
            </body>
</html>

注意:将选中的图片放大的插件地址是
https://github.com/keensoft/FullScreenImage-Cordova-Plugin

运行如下命令,添加到Cordova项目中
cordova plugin add https://github.com/keensoft/FullScreenImage-Cordova-Plugin.git

相关文章

网友评论

    本文标题:swift-使用Cordova自定义选择图片并压缩插件

    本文链接:https://www.haomeiwen.com/subject/nxvksttx.html