This may (or may not) be related to http://drupal.org/node/491208 it's hard to tell from that issue.

I've hit an issue where the incorrect width and height attributes are applied to an image. Basically you set the imagecache preset, click 'send to textarea' and the image is sent but the original image's height and width are supplied as attributes.

The image is displayed as the wrong size, the actual results will depend on what the preset does. In my case the preset scaled down and cropped the image using my http://drupal.org/project/im_raw module, but since the original dimensions were larger I ended up with an oversized and very pixellated image :)

I created some new presets that had a standard imagecache scale action, and those work as expected, retrieving the preset's size and applying it as width and height attributes.

I'll experiment a little more, and investigate, but at the moment I'd say the current template_preprocess_filefield_insert_widget() method of retrieving width and height might only work for imagecache presets with a defined size operation.

More later.

Comments

adrinux’s picture

Ok, a bit more info. These are the image tags generated with various settings.

Size set as original, gives the correct size:

<img src="/files/klassikmk/dnrm-low-edit_small.jpg" alt="" width="504" height="369" />

An image cache action scaling to a specified size results in imagecache adding a size to the array for that preset, filefield insert correctly retrieves and applies the width, and adjusts height:

<img src="/files/klassikmk/imagecache/col_3-177px/lvrm-h-l-08-crop-edit_small.jpg" alt="" width="177" height="90" />

Preset set to scale as 50%, generates an imagecached image with width 252px, but this is retrieved and added as 50px!

<img src="/files/klassikmk/imagecache/test/lvrm-lr-edit-small_0.jpg" alt="" width="50" height="28" />

A preset which should generate 177px wide square image via im_raw.module action, and thus doesn't add a size value to the preset array is either added as original size, or limited by filefield_insert max_width settings if larger as this image was:

<img src="/files/klassikmk/imagecache/item_index_thumbnail/lvrm-h-l-08-crop-edit.jpg" alt="" width="764" height="387" />

For the percentage gets inserted as pixel size bug, I'd suggest filefield_insert.js causes this in fileFieldInsert() by using parseInt as line 47 (and 48):

var width = parseInt($fileFieldElement.find('input.filefield-insert-width').val());

As for why the original size is used when no size is provided in the imagecache preset array, I'm not sure. It's clearly retrieving the size of the original file at line 122 of the module.

$image_info = image_get_info($item['filepath']);

But I can't figure why that's never replaced...any idea's?

jhl.verona’s picture

StatusFileSize
new3.18 KB

I experienced the same problems, though this is a very valuable module. I have made a quick fix, based on some code I was writing a while back which was going to do something similar to filefield_insert itself - just not as elegantly. I apologise for not having produced a diff or patch file, but I'm in a desperate rush right now - probably the normal state for a programmer...

quicksketch’s picture

jhl.verona, could you supply your changes as a patch? It's difficult to review what's changed in a completely different module archive. http://drupal.org/patch/create

jhl.verona’s picture

Hello quicksketch,

If I have time, I'll create a patch later. The reasoning is that I have made further modifications, I'm not using the CVS version, I'm using the filefield_insert-6.x-1.x-dev.tar.gz download, and I'm not at all familiar with PHP. Thank you for the link, I'll work my way through it in my copious free time, and thank you for the module, since you seem to be the author. It also appears from your resume', Nathan, that you're lightyears ahead of me in the Drupal sphere.

Explanation

This fairly short explanation of the reasoning behind the (hopefully final) modifications should allow you to make a better patch than my code.

it took me about two hours to realise that the problem has no simple solution (I was having a bad day, much like Wall Street). This is because ImageCache only creates the preset image when a browser attempts to retrieve it. In a node editing form, with one or more filefield (image) form fields, the original image, and a thumbnail are created when you upload, but no preset is created, so there is no preset image file to ask the dimensions for. Not a problem for the original image, of course, because it exists.

There are two solutions here, a quick hack, or much more code. The quick hack (guess which I chose) is to simply not provide width and height attributes for a non existant preset image. In other words, let the browser do a little more work. This results in the editor (I use TinyMCE via the Wysiwyg module) displaying the image at the correct size, and of course ImageCache is forced to create the preset image. The second solution would involve reading the ImageCache actions for the preset, and calculating the final image size. It would not be a good idea to actually create the images programmatically, since the ImageCache code is pretty sophisticated, and it could take a very long time (one or more seconds), apart from defeating the purpose of ImageCache itself. It would also create a heavy dependency on ImageCache, so if a new action was written, you'd have to add code to emulate the final image size.

One other problem I have is that I'm working on two sites, a straight domain on my local machine (to emulate the final production site), let's call it http://example.com, and a directory in another domain as a temporary (but Internet visible) site, let's say http://drupal.org/example. This causes inserted img links from one site to break on the other. I usually fix this URL link problem with Pathologic, which requires that you don't put a leading slash on the URL, for example "sites/default/files/..." not "/sites/default/files/...".

The modifications: filefield_insert.module

Understand that my knowledge of PHP and Drupal code is extremely limited, though I am a professional programmer (Java and Ruby mostly).
In the filefield_insert_process function, I added a line to store the image filepath, which is later retrieved by template_preprocess_filefield_insert_widget, thus (about line 55):

  $field['widget']['filefield_filepath'] = $item['filepath'];

To fix the broken link problem, using Pathologic, I changed the code which sets the filefield_insert_url form element (around line 107):

    $element['filefield_insert_url'] = array(
      '#id' => $element['#id'] . '-insert-url',
      '#name' => $element['#name'] . '[insert_url]',
      '#type' => 'hidden',
/*     I personally use Pathologic (http://drupal.org/project/pathologic), so I need to remove the base_path() value and leading '/' ...*/
/*    '#value'=> preg_replace('/^' . preg_quote($GLOBALS['base_url'] .'/', '/') . '/', base_path(), file_create_url($item['filepath'])), */
      '#value'=> preg_replace('/^' . preg_quote($GLOBALS['base_url'] .'/', '/') . '/', '', file_create_url($item['filepath'])),
      '#attributes' => array('class' => 'filefield-insert-url'),
    );

This works for me, because I alsways use Pathologic. It would be much better to check programmatically if the input format used for node editing has Pathologic enabled, or perhaps more simply that the Pathologic module is enabled. However, I'm not entirely sure how to do that.

Finally, in template_preprocess_filefield_insert_widget, I pick up the image filepath and attempt to get the ImageCache preset dimensions (around line 314):

      // Determine the final width/height.
      $width = 0;
      $height = 0;
      $filepath = $vars['field']['widget']['filefield_filepath'];
      $imagecache_path = imagecache_create_path($preset['presetname'], $filepath);
      if ($image = image_get_info($imagecache_path)) {
        $width = $image['width'];
        $height = $image['height'];
      }

Here endeth the PHP modifications.

The modifications: filefield_insert.js

I'm reasonably comfortable with JavaScript, so these changes are not so hackish.
I simplified the preset test (around line 59) to just grab the dimensions (even if they are 0):

    // Update the URL if using a preset.
    if (preset) {
      var pieces = preset.split('|');
      url = url.replace(fileDir + '/', fileDir + '/imagecache/' + pieces[0] + '/');
      width = parseInt(pieces[1]);
      height = parseInt(pieces[2]);
    }

Then I lobotomise the insert text removing the width and height attributes if their values are 0 (around line 90, line 110 in the original code):

    // Poor man's escaping of invalid characters in the URL.
    url = encodeURI(url).replace(/([#$*(),?])/g, function(match) { return escape(match) });

    // Modified: remove width="0" and height="0"
    if (width == 0 || height == 0) {
      content = content.replace(/width=\"__width__\"/g, '').replace(/height=\"__height__\"/g, '');
    }

Hope that helps,
John

jhl.verona’s picture

StatusFileSize
new4.83 KB

quicksketch,

Here is the patch file. The only (other) modification I have made to the above description is to add a orgUrl variable to the JavaScript, which I am using to generate anchor links to the original image for Lightbox - I modified filefield-insert-image.tpl.php after copying it to my theme folder. Works like a charm.

John

[Edit 2009-10-07] I have made a slight improvement to the patch, specifically to make it Pathologic friendly, it's just a few comments further down.

John

giorgosk’s picture

Applied patch but it actually gives me all images with the width and height of the original image
no matter what preset I chose

jhl.verona’s picture

StatusFileSize
new5.78 KB

@GiorgosK
Sorry to have taken such a long time to reply. I have given the code a full test today with the following results:
1. Taking filefield_insert from the CVS repository, I still get the deformed image problem that this thread pointed out.
2. I applied the patch, and then created a new node.
3. As you have pointed out, any preset gives the original image height/width *but*,
4. Checking the JavaScript code, I found that the patched file was *not* being used.
5. Either using admin_menu "Flush all caches", or admin/settings/performance "Clear cached data" button, clear all the caches.
6. Try again with a new node, and things should work correctly, as they did for me.

To make sure your using the right JavaScript file, use firebug to check the filefield_insert.js file, which should have the following code:

91 // Poor man's escaping of invalid characters in the URL.
92 url = encodeURI(url).replace(/([#$*(),?])/g, function(match) { return escape(match) });
93
94 // Remove width="0" and height="0"
95 if (width == 0 || height == 0) {
96 content = content.replace(/width=\"__width__\"/g, '').replace(/height=\"__height__\"/g, '');
97 }

HTH

Since I was playing around with the patch, I have included a test for the Pathologic module (which I use frequently) so that the image URL will be Pathologic friendly.
I am including this new patch with this post.

John

giorgosk’s picture

@jhl.verona

I would swear that I have cleared cache but maybe I did not

now it seems to behave as it should
the correct imagecache image gets inserted with the right dimensions

But,
The width and height are not inserted in the image tag (Only local images are allowed. width and height)
is that how it should be ?

jhl.verona’s picture

Yes, it's a hack, because the image doesn't actually exist when you insert the text. ImageCache creates these images on demand.
See the explanation above. Second paragraph, titled, er, "Explanation" ;-)

If you find that estectically displeasing, you can always preview the node (which will trigger the creation of the cached images) and then insert the image text again, deleting the old text, of course.
This time round, the image exists, and so filefield_insert will add the correct dimensions.

I'm not going to explain that to my clients though and I don't personally think the 'hack' is really all that bad.

Excellent module, btw. Makes my life much easier.

HTH

John

giorgosk’s picture

Status: Active » Reviewed & tested by the community

Great hack john
and after your explanation, it works as expected, I really don't mind all the much about the dimensions

I would love to see this committed

quicksketch’s picture

Status: Reviewed & tested by the community » Needs review

Hm, well the current approach is a bit of a hack too (and has obvious dimension problems when using percentages), I'm not sure if this is truly better. Then again, end-users don't really care about proper HTML and this module is definitely intended to serve them over XHTML fanatics.

quicksketch’s picture

Project: FileField Insert » Insert
Version: 6.x-1.x-dev » 6.x-1.0-beta1
Status: Needs review » Fixed

I've simply removed the height/width tags from ImageCache preset inserts in the new version of this module, which I've renamed to just Insert, since it doesn't specifically require FileField. Please reopen if you find any troubles with the new module with ImageCache width/height.

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

philbar’s picture

Status: Closed (fixed) » Needs work

Duplicate: #741368: Performance: Specify image dimensions

Re-opened to re-introduce size attributes for imagecache presets. Size attributes increase website performance by eliminating the need for unnecessary reflows and repaints (source).

quicksketch’s picture

I think this is by design, for the reasons stated above.

geerlingguy’s picture

Subscribe...? Please also see my comment (#7) here: #549966: Remove Width and Height attributes when using Image Cache preset

Specifically, one of my ImageCache Presets is set to add a class to the image for captioning (using the title/alt text); however, since no width is set, the containing div for the caption expands to the width of the caption sentance(s), which is not desirable.

Right now, I have to manually add in the width and height attributes for every image I insert with the Caption preset.

bryancasler’s picture

I also would like to see the option to have the height and width maintained after being inserted with an image cache setting.

quicksketch’s picture

Title: Width and Height are not always correctly retrieved for an imagecache preset » Calculate width and height attributes when inserting ImageCache images

Updating the title to reflect what this issue has become.

A solution I'd like to recommend, is a recent change to Image Resize Filter (a great companion to Insert module): #765194: Always add height and width attributes even when not resizing. This adds the height/width attributes on output instead of on input, meaning that if you did ever change an ImageCache preset size, all locations where that preset was used in posts on the whole site would automatically be adjusted to the new size.

geerlingguy’s picture

That would be perfect, actually...

quicksketch’s picture

Status: Needs work » Closed (fixed)

Great, so now that we have a solution (even though it's not in Insert) I hope that satisfies people's requests.

bryancasler’s picture

Its been working for me