项目需要访问系统相册上传图片,记录下ios下访问相册的代码
使用luaoc 在lua和oc交互调用
//打开本地相册
- (void)LocalPhoto
{
// 弹出系统的相册
// 选择控制器(系统相册)
UIImagePickerController * picker = [[UIImagePickerController alloc] init];
// 设置选择控制器的来源
// UIImagePickerControllerSourceTypePhotoLibrary 相册集
// UIImagePickerControllerSourceTypeSavedPhotosAlbum:照片库
picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
// 设置代理
picker.delegate = (id)self;
// modal
[self presentViewController:picker animated:YES completion:nil];
}
///
-(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth
{
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = defineWidth;
CGFloat targetHeight = (targetWidth / width) * height;
UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
[sourceImage drawInRect:CGRectMake(0,0,targetWidth, targetHeight)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
//当选择的类型是图片
if ([type isEqualToString:@"public.image"])
{
//先把图片转成NSData
UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
image = [self imageCompressForWidth:image targetWidth:600];
NSData *data;
if (UIImagePNGRepresentation(image) == nil)
{
data = UIImageJPEGRepresentation(image, 0.5);
}
else
{
data = UIImagePNGRepresentation(image);
}
//图片保存的路径
//这里将图片放在沙盒的documents文件夹中
NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//文件管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *fileName = [NSString stringWithFormat:@"/%@%d.png",@"launch_img",_launchIndex];
NSLog(@"图片名称是:%@", fileName);
//把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
[fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
[fileManager createFileAtPath:[DocumentsPath stringByAppendingString: fileName] contents:data attributes:nil];
//得到选择后沙盒中图片的完整路径
NSString* filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,fileName];
_launchIndex += 1;
//关闭相册界面
[picker dismissModalViewControllerAnimated:YES];
NSLog(@"图片的路径是:%@", filePath);
//图片2进制路径
//strFilePath = [filePath UTF8String];
const char * filePathChar = [filePath UTF8String];
/
int scriptHandler = [[LaunchCameraManager getInstance] getScriptHandler];
if (scriptHandler)
{
LuaBridge::pushLuaFunctionById(scriptHandler);
LuaStack *stack = LuaBridge::getStack();
stack->pushString(filePathChar);
stack->executeFunction(1);
}
}
}
例子代码下载地址: