Skip to content

Instantly share code, notes, and snippets.

@cmrockwell
Last active October 1, 2015 14:48
Show Gist options
  • Save cmrockwell/69380afd31194ac3a000 to your computer and use it in GitHub Desktop.
Save cmrockwell/69380afd31194ac3a000 to your computer and use it in GitHub Desktop.
AEM WF Step to make optimized PNG
package com.r2i.michigan.lsa.services.osgi.workflow;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.osgi.framework.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.commons.process.AbstractAssetWorkflowProcess;
import com.day.cq.workflow.WorkflowException;
import com.day.cq.workflow.WorkflowSession;
import com.day.cq.workflow.exec.WorkItem;
import com.day.cq.workflow.metadata.MetaDataMap;
import com.tinify.Source;
import com.tinify.Tinify;
//import com.adobe.granite.workflow.metadata.MetaDataMap;
//import com.adobe.granite.asset.api.Asset;
//import com.adobe.granite.workflow.WorkflowException;
//import com.adobe.granite.workflow.WorkflowSession;
//import com.adobe.granite.workflow.exec.WorkItem;
@Component
@Service
@Properties({
@Property(name = Constants.SERVICE_DESCRIPTION, value = "LSA Compress Assets with TinyPNG"),
@Property(name = Constants.SERVICE_VENDOR, value = "U-M LSA"),
@Property(name = "process.label", value = "LSA Compress Assets") })
public class Compress extends AbstractAssetWorkflowProcess { //implements WorkflowProcess
static private final String APIKEY = "blahblah123";
protected final Logger log = LoggerFactory.getLogger(this.getClass());
@Override
public void execute(WorkItem item, WorkflowSession wfSession, MetaDataMap args)
throws WorkflowException {
final Asset asset = getAssetFromPayload(item, wfSession.getSession());
String assetPath = (String) item.getWorkflowData().getPayload();
log.info("UM LSA ASSET STEP ON "+assetPath );
Tinify.setKey(APIKEY);
String mt = asset.getMimeType();
InputStream is =asset.getRendition("original").getStream();
InputStream fromIS = null;
try {
byte[] bytes = IOUtils.toByteArray(is);
Source source = Tinify.fromBuffer(bytes);
byte[] optimized = source.toBuffer();
fromIS = new ByteArrayInputStream(optimized);
asset.addRendition("optimized", fromIS, mt);
} catch (IOException e) {
log.error("TINYPNG ERROR", e);
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(fromIS);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment