1. 程式人生 > >phonegap(cordova) 自定義外掛程式碼篇(四)----讀取本地圖片

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