编辑于2019-06-28 。
正常来讲,直接用这个方法
NSData *imageData = [NSData dataWithContentsOfFile:path];//path为 blob:file:///XXXXX
来处理的话, imageData的值为空,可以这么试试,曲线救国
1.用js方法,将image转成base64字符
下边代码可以直接保存成html文件测试,不过需要解决下跨域问题,推荐使用Chrome浏览器,
解决方法: Mac上解决Chrome浏览器跨域问题
\\\\\\\\\\\\\\\\\\HTML测试代码\\\\\\\\\\\\\\\\\\\\
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<title>js 图片转base64方式</title>
</head>
<body>
<img id="image" src="img.png">
<img id="image" src="img2.png">
<img id="image" src="img3.png">
<button onclick="getBase64Str();"> 获取 </button>
<p id="container2"></p>
<script type = "text/javascript">
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
var dataURL = canvas.toDataURL("image/"+ext);
return dataURL;
}
function getBase64Str() {
var imgSrc = "file:///Users/ruanmei/Desktop/1/img.png";
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i) {
var image = images[i];
console.log(image.src);
if (image.src ==imgSrc) {
var base64 = getBase64Image(image);
console.log(base64);
}
i++;
}
}
</script>
</body>
</html>
\\\\\\\\\\\\\\\\\\JS代码\\\\\\\\\\\\\\\\\\\
JS代码
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
var dataURL = canvas.toDataURL("image/"+ext);
return dataURL;
}
\\\\\\\\\\\\\\\\\\OC代码\\\\\\\\\\\\\\\\\\\\
//这个方法可以放到webview的类目中
- (NSString *)getBase64ImageWithURL:(NSString *)imageURL{
NSString *trigger = [NSString stringWithFormat:@"getBase64Image(\"%@\");",imageURL];
NSString * base64Str = [self stringByEvaluatingJavaScriptFromString:trigger];
return base64Str;
}
2.将转换出来的base64字符转换为NSData
这一步就简单了
//获取到base64字符串
NSString * Base64Str = [self.webview getBase64ImageWithURL:homePath];
NSURL * baseImageUrl = [NSURL URLWithString:Base64Str];//先转化为NSURL
NSData * imageData = [NSData dataWithContentsOfURL:baseImageUrl];//base64字符串转data
完成。
\\\\\\\\\\\\\\\\\\更新\\\\\\\\\\\\\\\\\\\
这个方法支持memoji输入
网友评论