Skip to content

Embedding images in HTML rendered message

dinhviethoa edited this page Nov 13, 2014 · 1 revision

Using the iOS example, here's some alternative tweaks to embed the images inline in the HTML instead of referring to files.

-(void)loadInlineImagesforWebView:(UIWebView*)webView
{
	NSString * result = [webView stringByEvaluatingJavaScriptFromString:@"findCIDImageURL()"];
	NSData * data = [result dataUsingEncoding:NSUTF8StringEncoding];
	NSError *error = nil;
	NSArray * imagesURLStrings = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
	
	for(NSString * urlString in imagesURLStrings) {
		MCOAbstractPart * part = nil;
		NSURL * url;
		
        
		url = [NSURL URLWithString:urlString];
		if ([self isCID:url]) {
			part =  [self partForContentID:[url resourceSpecifier]];
		}
		else if ([self isXMailcoreImage:url]) {
			NSString * specifier = [url resourceSpecifier];
			NSString * partUniqueID = specifier;
			part = [self partForUniqueID:partUniqueID];
		}
		
		if (part == nil)
			continue;
		
		NSString * partUniqueID = [part uniqueID];

        NSData * previewData = [self dataPartForUniqueID:partUniqueID];

        NSString *inlineData = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[previewData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];
        
        NSDictionary * args = @{@"URLKey": urlString, @"InlineDataKey": inlineData };
        
        NSString * jsonString = [self _jsonEscapedStringFromDictionary:args];
        
        NSString * replaceScript = [NSString stringWithFormat:@"replaceImageSrc(%@)", jsonString];
        [webView stringByEvaluatingJavaScriptFromString:replaceScript];
        
	}
}

- (NSString *) _jsonEscapedStringFromDictionary:(NSDictionary *)dictionary
{
	NSData * json = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:nil];
	NSString * jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
	return jsonString;
}

- (NSURL *) _cacheJPEGImageData:(NSData *)imageData withFilename:(NSString *)filename
{
	NSString * path = [[NSTemporaryDirectory() stringByAppendingPathComponent:filename] stringByAppendingPathExtension:@"jpg"];
	[imageData writeToFile:path atomically:YES];
	return [NSURL fileURLWithPath:path];
}


-(BOOL) isCID:(NSURL *)url
{
	NSString *theScheme = [url scheme];
	if ([theScheme caseInsensitiveCompare:@"cid"] == NSOrderedSame)
        return YES;
    return NO;
}

- (BOOL) isXMailcoreImage:(NSURL *)url
{
	NSString *theScheme = [url scheme];
	if ([theScheme caseInsensitiveCompare:@"x-mailcore-image"] == NSOrderedSame)
        return YES;
    return NO;
}


-(MCOAttachment*)partForContentID:(NSString*)partUniqueID{
    
    MCOMessageParser *parser = [MCOMessageParser messageParserWithData:self.mailBodyData];
    [parser htmlBodyRendering];
    MCOAttachment * attachment = (MCOAttachment *) [parser partForContentID:partUniqueID];
    return attachment;
}

-(MCOAttachment*)partForUniqueID:(NSString*)partUniqueID{
    
    MCOMessageParser *parser = [MCOMessageParser messageParserWithData:self.mailBodyData];
    [parser htmlBodyRendering];
    MCOAttachment * attachment = (MCOAttachment *) [parser partForUniqueID:partUniqueID];
    return attachment;
}

-(NSData*)dataPartForUniqueID:(NSString*)partUniqueID{
    
    MCOMessageParser *parser = [MCOMessageParser messageParserWithData:self.mailBodyData];
    [parser htmlBodyRendering];
    MCOAttachment * attachment = (MCOAttachment *) [parser partForUniqueID:partUniqueID];
    return [attachment data];
}


------in Script section of HTML template we will have next functions ----
var imageElements = function() {
    var imageNodes = document.getElementsByTagName('img');
    return [].slice.call(imageNodes);
};

var findCIDImageURL = function() {
    var images = imageElements();
    
    var imgLinks = [];
    for (var i = 0; i < images.length; i++) {
        var url = images[i].getAttribute('src');
        if (url.indexOf('cid:') == 0 || url.indexOf('x-mailcore-image:') == 0)
        imgLinks.push(url);
    }
    return JSON.stringify(imgLinks);
};

var replaceImageSrc = function(info) {
    var images = imageElements();
    
    for (var i = 0; i < images.length; i++) {
        var url = images[i].getAttribute('src');
        if (url.indexOf(info.URLKey) == 0) {
            images[i].setAttribute('src', info.InlineDataKey);
            break;
        }
    }
};
Clone this wiki locally