1

Is it possible to resize images in a Rich Text Field?

We need to add images to a rich text field we have, but we found out we couldn't do any resizing.

Is resizing possible in Salesforce rich text field? Or is this a limitation?

Edit: This is the rich text editor that I see: enter image description here

2 Answers 2

3

You can do it with Apex. If you have only 1 image in the text you can use the following sample code.

String contactId;
Contact c = [
        SELECT Id, Picture__c
        FROM Contact
        WHERE Id = :contactId
];

c.Picture__c = c.Picture__c.replace('<img', '<img style="height: 256px"');

update contacts;

Note: update SObject name and field name

If you have more than 1 image you might want to add better search strings

3
  • 1
    Presumably that is lost if further interactive editing is done?
    – Keith C
    Sep 25, 2019 at 9:09
  • 1
    No, for some reason it is saved. Even when you update the content of the field
    – ytiq
    Sep 25, 2019 at 10:27
  • Good to know - thanks!
    – Keith C
    Sep 25, 2019 at 12:30
2

The answer from ytiq was excellent, and really helped me solve a similar problem.

What I found is that if his code gets run multiple times, it will add multiple copies of the "style="height: XXX" tag, and the first one added will take precedence over any subsequent ones.

Pasted below is some more elaborate code that takes care of that issue:

    public static void resizeProfilePhoto(integer pixelsWide, string contactID) {
    Contact c = [
        SELECT Id, Profile_Photo__c
        FROM Contact
        WHERE Id = :contactId
    ];
    if (c.Profile_Photo__c != null) {
        //system.debug('field before ' + c.Profile_Photo__c);
        string newTag = '<img style="height: ' + pixelsWide + 'px"';
        if (c.Profile_Photo__c.startsWith('<p><img style="height:')) {
            c.Profile_Photo__c = c.Profile_Photo__c.replaceFirst('<img style="height: [0-9]*px;"', newTag);
            system.debug('Found existing size - field after ' + c.Profile_Photo__c);
        } else {
            c.Profile_Photo__c = c.Profile_Photo__c.replace('<img', newTag);
            system.debug('field after ' + c.Profile_Photo__c);
        }
        update c;
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .