001/* 002 * Copyright 2013 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.cms.transformation; 017 018import java.io.ByteArrayOutputStream; 019import java.io.IOException; 020import java.io.InputStream; 021 022import org.apache.commons.codec.binary.Base64; 023import org.apache.commons.io.IOUtils; 024import org.apache.commons.lang.StringUtils; 025 026import org.ametys.core.util.ImageHelper; 027 028/** 029 * Class providing helper methods to resolve images. 030 */ 031public final class ImageResolverHelper 032{ 033 034 private ImageResolverHelper() 035 { 036 // Hides the default constructor. 037 } 038 039 /** 040 * Get an image's bytes encoded as base64, optionally resized. 041 * @param dataIs an input stream on the image bytes. 042 * @param mimeType the image mime type. 043 * @param height the specified height. Ignored if negative. 044 * @param width the specified width. Ignored if negative. 045 * @param maxHeight the maximum image height. Ignored if height or width is specified. 046 * @param maxWidth the maximum image width. Ignored if height or width is specified. 047 * @return the image bytes encoded as base64. 048 * @throws IOException if an error occurs. 049 */ 050 public static final String resolveImageAsBase64(InputStream dataIs, String mimeType, int height, int width, int maxHeight, int maxWidth) throws IOException 051 { 052 if (!mimeType.startsWith("image/")) 053 { 054 return ""; 055 } 056 057 ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 058 059 if (height == 0 && width == 0 && maxHeight == 0 && maxWidth == 0) 060 { 061 IOUtils.copy(dataIs, buffer); 062 } 063 else 064 { 065 String format = StringUtils.substringAfter(mimeType, "/"); 066 ImageHelper.generateThumbnail(dataIs, buffer, format, height, width, maxHeight, maxWidth); 067 } 068 069 String data = Base64.encodeBase64String(buffer.toByteArray()); 070 071 return "data:" + mimeType + ";base64," + data; 072 } 073 074}