zoukankan      html  css  js  c++  java
  • phonegap(cordova) 自己定义插件代码篇(四)----读取本地图片

    有时候确实知道本地图片地址,要获取到base64 

    /**
     * 获取本地图片,包括路径和压缩后的 base64  
     */
    
    (function (cordova) {
        var define = cordova.define;
    
        define("cordova/plugin/localImage", function (require, exports, module) {
            var argscheck = require('cordova/argscheck'),
    	    exec = require('cordova/exec');
            exports.getImage = function (localFileUrl, successCB, failCB) {
    
                exec(successCB, failCB, "LocalImage", "getImage", [localFileUrl]);
    
            };
    
        });
        cordova.addConstructor(function () {
            if (!window.plugins) {
                window.plugins = {};
            }
            console.log("将插件注入localImage...");
            window.plugins.localImage = cordova.require("cordova/plugin/localImage");
            console.log("localImage注入结果:" + typeof (window.plugins.localImage));
    
        });
    })(cordova);

    android

    public class LocalImagePlugin extends CordovaPlugin {
    	@Override
    	public boolean execute(String action, JSONArray args,
    			CallbackContext callbackContext) throws JSONException {
    
    		if ("getImage".equals(action)) {
    
    			String localFileUrl = args.getString(0).replace("file:///", "/");
    //			Log.i("our", localFileUrl);
    			String file = "{"path":"" + localFileUrl + "","data":""
    					+ bitmapToString(localFileUrl) + ""}";
    //			Log.i("our", file);
    			callbackContext.success(file);
    			return true;
    
    		} else {
    			return false;
    		}
    	}
    
    	public static String bitmapToString(String filePath) {
    
    		Bitmap bm = getSmallBitmap(filePath);
    		ByteArrayOutputStream baos = new ByteArrayOutputStream();
    		bm.compress(Bitmap.CompressFormat.JPEG, 50, baos);
    		byte[] b = baos.toByteArray();
    		return Base64.encode(b);
    	}
    
    	// 依据路径获得图片并压缩。返回bitmap用于显示
    	public static Bitmap getSmallBitmap(String filePath) {
    		final BitmapFactory.Options options = new BitmapFactory.Options();
    		options.inJustDecodeBounds = true;
    		BitmapFactory.decodeFile(filePath, options);
    
    		// Calculate inSampleSize
    		options.inSampleSize = calculateInSampleSize(options, 480, 800);
    
    		// Decode bitmap with inSampleSize set
    		options.inJustDecodeBounds = false;
    
    		return BitmapFactory.decodeFile(filePath, options);
    	}
    
    	// 计算图片的缩放值
    	public static int calculateInSampleSize(BitmapFactory.Options options,
    			int reqWidth, int reqHeight) {
    		final int height = options.outHeight;
    		final int width = options.outWidth;
    		int inSampleSize = 1;
    
    		if (height > reqHeight || width > reqWidth) {
    			final int heightRatio = Math.round((float) height
    					/ (float) reqHeight);
    			final int widthRatio = Math.round((float) width / (float) reqWidth);
    			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    		}
    		return inSampleSize;
    	}
    }

    iOS 

    #import <UIKit/UIKit.h>
    #import <Cordova/CDV.h>
    
    @interface CDVLocalImage: CDVPlugin
    
    @property (nonatomic,copy) NSString*callbackID;
    //Instance Method
    -(void) getImage:(CDVInvokedUrlCommand*)command ;
    
    @end

    #import "CDVLocalImage.h"
    #import "TencentOpenAPI/QQApiInterface.h"
    #import <TencentOpenAPI/TencentOAuth.h>
    @implementation CDVLocalImage
    @synthesize callbackID;
    -(void)getImage:(CDVInvokedUrlCommand *)command
    
    {
        //url
        NSString* localImageUrl = [command.arguments objectAtIndex:0];
        
               localImageUrl =[localImageUrl stringByReplacingOccurrencesOfString:@"file://" withString:@""];
        
        NSData *mydata=UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:localImageUrl], 0.5);
        NSString *pictureDataString=[mydata base64Encoding];
        
        NSString *file =[NSString stringWithFormat:@"{"path":"%@","data":"%@"}", localImageUrl,pictureDataString];
    
        
    //       NSLog(@"selected >>>>%@",file);
        
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:file];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
    @end
    


  • 相关阅读:
    Ubuntu Linux markdown编辑工具 typora 安装
    ref以及传值传址的理解
    3. 无重复字符的最长子串
    30. 串联所有单词的子串 (哈希+滑动窗口)
    525. 连续数组 (哈希表)
    438. 找到字符串中所有字母异位词 (滑动窗口)
    451、根据字符出现频率排序(哈希 加优先队列)
    743. 网络延迟时间
    310. 最小高度树
    8皇后问题
  • 原文地址:https://www.cnblogs.com/llguanli/p/8456583.html
Copyright © 2011-2022 走看看