Change image tag generated by CKEditor
For a new project of mine I’m using a rich text editor called CKEditor.
This is a highly configurable editor that, unfortunately, suffers from cluttered and not easily understandable documentation.
I needed to change the generated HTML from the editor so that images that were resized not only had their size set as style attributes, but as query string variables.
So I needed this:
<img src=”http://yoursite.com/photo.jpg” style=”width:150px; height:200px;” />
to be output as this:
<img src=”http://yoursite.com/photo.jpg?width=150&height=200″ style=”width:150px; height:200px;” />
That proved to be easier said than done, but after quite a lot of googling, asking on several forums, and getting some helpful (and some not helpful at all) replies, I finally ended up with the following:
Put the following code into CKEditor’s config.js:
CKEDITOR.on('instanceReady', function (ev) { var editor = ev.editor, dataProcessor = editor.dataProcessor, htmlFilter = dataProcessor && dataProcessor.htmlFilter; htmlFilter.addRules( { elements : { $ : function( element ) { // Output dimensions of images as width and height attributes on src if ( element.name == 'img' ) { var style = element.attributes.style; if (style) { // Get the width from the style. var match = /(?:^|\s)width\s*:\s*(\d+)px/i.exec( style ), width = match && match[1]; // Get the height from the style. match = /(?:^|\s)height\s*:\s*(\d+)px/i.exec( style ); var height = match && match[1]; var imgsrc = element.attributes.src + "?width=" + width + "&height=" + height; element.attributes.src = imgsrc; element.attributes['data-cke-saved-src'] = imgsrc; } } } } }); });
This code is run whenever the CKEditor generates the actual HTML, which happens when you either view the source by clicking the “Source” button, or by performing an HTTP POST of that page.
A small warning, though. The code above will keep appending the width and height query strings for each click on the “Source” button, or for each postback, so you might want to add some extra logic to filter out the width and height query strings before appending them to the src attribute. (I might edit this post in the future with the correct syntax for that ;))