美文网首页
IOS 提取HTML的图片或修改图片样式

IOS 提取HTML的图片或修改图片样式

作者: 请输入昵称Arthas | 来源:发表于2018-09-07 12:01 被阅读0次

    想提取图片还是样式,以下方法已经满足的了,自己简单修改一下就可以了

    /**
     过滤HTML字符串中的图片指定宽度
     
     @param width 宽度
     @return result
     */
    - (NSString *)htmlWebAutoImageSizeWidth:(CGFloat)width{
        if (self == nil || self.length == 0) {
            return @"";
        }
        NSString *content = [self stringByReplacingOccurrencesOfString:@"&quot" withString:@"'"];
        content = [content stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
        content = [content stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
        content = [content stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
        
        
        NSString *html = content;
        NSString * regExpStr = @"<(img|IMG)[^\\<\\>]*>";
        NSRegularExpression *regex=[NSRegularExpression regularExpressionWithPattern:regExpStr options:NSRegularExpressionCaseInsensitive error:nil];
        
        NSArray *matches=[regex matchesInString:html
                                        options:0
                                          range:NSMakeRange(0, [html length])];
        
        //HTML中的<img ...... />数组
        NSMutableArray *imgArray = [NSMutableArray array];
        //<img src="URL"/>中的URL数组
        NSMutableArray *urlArray = [NSMutableArray array];
        
        for (NSTextCheckingResult *result in matches) {
            NSRange range   = result.range;
            NSString *group = [html substringWithRange:range];
            NSRange srange1 = [group rangeOfString:@"http"];
            NSString *tempString1 = [group substringWithRange:NSMakeRange(srange1.location, group.length - srange1.location)];
            NSRange srange2 = [tempString1 rangeOfString:@"\""];
            NSString *tempString2 = [tempString1 substringWithRange:NSMakeRange(0,srange2.location)];
            [urlArray addObject:tempString2];
            [imgArray addObject:group];
        }
        
        for (int i = 0; i < imgArray.count; i++) {
            NSString *string = imgArray[i];
            //[NSDate timeStamp] 这个方法是获取时间戳的
            html = [html stringByReplacingOccurrencesOfString:string withString:[NSString stringWithFormat:@"<img src=\"%@\" title=\"\" alt=\"%lld\" width=\"%f\" height=\"auto\">",urlArray[i],[NSDate timeStamp]+i,width]];
        }
        
        
        return html;
    }
    

    相关文章

      网友评论

          本文标题:IOS 提取HTML的图片或修改图片样式

          本文链接:https://www.haomeiwen.com/subject/omzqgftx.html