从HTML获取图像大小

时间:2012-01-08 18:27:52

标签: html ios uiwebview

我正在从博客中解析RSS源,并将帖子的HTML放在UIWebView内。

但是现在我想改变图像的大小以适应iPhone屏幕。我正在尝试以下替换

HTMLContent = [HTMLContent stringByReplacingOccurrencesOfString:@"width=\"480\"" withString:@"width=\"300\""];

但这样做我只更换480宽度的图像。而且我不会改变高度!

你知道是否有办法用300替换任何宽度,并用同样的因子改变高度?

1 个答案:

答案 0 :(得分:3)

您可以使用正则表达式执行此操作。您希望匹配字符串中的<img>标记并提取高度和宽度值,然后计算新的所需高度和宽度,然后使用新值替换字符串中的高度和宽度。

以下代码应该可以使用,但可能会遗漏一些边缘情况(例如,如果height属性出现在img标记中的width属性之前)。

int maxWidth = 300;
NSString *originalHTML = @"<html><body><img src='image1.gif' width='4800' height='80' alt='foobar'/><img src='image1.gif' width='70000' height='99999' alt='foobar'/></body></html>";

NSString *regexPattern = @"<img[^>]*width=['\"\\s]*([0-9]+)[^>]*height=['\"\\s]*([0-9]+)[^>]*>";

NSRegularExpression *regex = 
[NSRegularExpression regularExpressionWithPattern:regexPattern 
                                          options:NSRegularExpressionDotMatchesLineSeparators 
                                            error:nil];

NSMutableString *modifiedHTML = [NSMutableString stringWithString:originalHTML];

NSArray *matchesArray = [regex matchesInString:modifiedHTML 
                                   options:NSRegularExpressionCaseInsensitive 
                                     range:NSMakeRange(0, [modifiedHTML length]) ]; 

NSTextCheckingResult *match;

// need to calculate offset because range position of matches
// within the HTML string will change after we modify the string
int offset = 0, newoffset = 0;

for (match in matchesArray) {

    NSRange widthRange = [match rangeAtIndex:1];
    NSRange heightRange = [match rangeAtIndex:2];

    widthRange.location += offset;
    heightRange.location += offset;

    NSString *widthStr = [modifiedHTML substringWithRange:widthRange];
    NSString *heightStr = [modifiedHTML substringWithRange:heightRange];

    int width = [widthStr intValue];
    int height = [heightStr intValue];

    if (width > maxWidth) {
        height = (height * maxWidth) / width;
        width = maxWidth;

        NSString *newWidthStr = [NSString stringWithFormat:@"%d", width];
        NSString *newHeightStr = [NSString stringWithFormat:@"%d", height];

        [modifiedHTML replaceCharactersInRange:widthRange withString:newWidthStr];

        newoffset = ([newWidthStr length] - [widthStr length]);
        heightRange.location += newoffset;

        [modifiedHTML replaceCharactersInRange:heightRange withString:newHeightStr];                

        newoffset += ([newHeightStr length] - [heightStr length]);            
        offset += newoffset;
    }
}

NSLog(@"%@",modifiedHTML);