How to crop an image to a rectangle in Salesforce Apex
1 min readJul 11, 2020
Image cropping is a useful feature in many situations, but its implementation isn’t always the smoothest when working with Salesforce Apex. To put it bluntly, it’s a quagmire just waiting to suck you in for hours if you are not careful. Instead of dealing with that, how about I show you how to get cropping done fast using an API.
To use our API, first download this zip archive and copy the client folder into your Apex project:
https://github.com/Cloudmersive/Cloudmersive.APIClient.Apex.ImageRecognition/archive/master.zip
Now we will call our crop function and specify our dimensions and location of the crop:
SwagEditApi api = new SwagEditApi();SwagClient client = api.getClient();// Configure API key authorization: ApikeyApiKeyAuth Apikey = (ApiKeyAuth) client.getAuthentication('Apikey');Apikey.setApiKey('YOUR API KEY');Map<String, Object> params = new Map<String, Object>{'left' => 56,'top' => 56,'width' => 56,'height' => 56,'imageFile' => Blob.valueOf('Sample text file\nContents')};try {// cross your fingersBlob result = api.editCropRectangle(params);System.debug(result);} catch (Swagger.ApiException e) {// ...handle your exceptions}
And it’s as easy as that!