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
    


  • 相关阅读:
    acdream.18.KIDx's Triangle(数学推导)
    upc.2219: A^X mod P(打表 && 超越快速幂(in some ways))
    山东省第四届acm.Rescue The Princess(数学推导)
    BC.5200.Trees(dp)
    BC.36.Gunner(hash)
    hdu.5195.DZY Loves Topological Sorting(topo排序 && 贪心)
    数组倒置算法扩展
    C# 传值和传引用 ( ref out in )
    C# 输出文件夹下的所有文件
    控制反转(自译)
  • 原文地址:https://www.cnblogs.com/llguanli/p/8456583.html
Copyright © 2011-2022 走看看