public BasicImageRewriter(OptimizerConfig config) {
this.config = config;
}
public HttpResponse rewrite(HttpRequest request, HttpResponse response) {
Uri uri = request.getUri();
if (uri == null || request == null || response == null)
return response;
try {
// Check resizing
Integer resizeQuality = request.getParamAsInteger(PARAM_RESIZE_QUALITY);
Integer requestedWidth = request.getParamAsInteger(PARAM_RESIZE_WIDTH);
Integer requestedHeight = request.getParamAsInteger(PARAM_RESIZE_HEIGHT);
boolean isResizeRequested = (requestedWidth != null || requestedHeight != null);
// If the path or MIME type don't match, continue
if (!isSupportedContent(response) && !isImage(uri)) {
return response;
}
if (!isUsableParameter(requestedWidth) || !isUsableParameter(requestedHeight)
|| !isUsableParameter(resizeQuality)) {
return response;
}
// Content header checking is fast so this is fine to do for every response.
ImageFormat imageFormat = Sanselan
.guessFormat(new ByteSourceInputStream(response.getResponse(), uri.getPath()));
if (imageFormat == ImageFormat.IMAGE_FORMAT_UNKNOWN) {
return enforceUnreadableImageRestrictions(uri, response);
}
// Don't handle very small images, but check after parsing format to
// detect attacks.
if (response.getContentLength() < config.getMinThresholdBytes()) {
return response;
}
ImageInfo imageInfo = Sanselan.getImageInfo(response.getResponse(), uri.getPath());
boolean isOversizedImage = isImageTooLarge(imageInfo);
if (isResizeRequested && isOversizedImage) {
HttpResponseBuilder rejectedResponseBuilder = new HttpResponseBuilder()
.setHttpStatusCode(HttpResponse.SC_FORBIDDEN)