ThumbnailGenerator1.java

/*
 * Copyright 2018 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.genesys.filerepository.service.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.genesys.filerepository.service.ThumbnailGenerator;
import org.springframework.stereotype.Service;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;
import net.coobird.thumbnailator.geometry.Positions;
import net.coobird.thumbnailator.resizers.configurations.AlphaInterpolation;
import net.coobird.thumbnailator.resizers.configurations.Antialiasing;
import net.coobird.thumbnailator.resizers.configurations.Rendering;
import net.coobird.thumbnailator.resizers.configurations.ScalingMode;

/**
 * Thumbnail generator using Thumbnailator
 * https://github.com/coobird/thumbnailator
 */
@Service
public class ThumbnailGenerator1 implements ThumbnailGenerator {

	/*
	 * (non-Javadoc)
	 * @see
	 * org.genesys.filerepository.service.ThumbnailGenerator#createThumbnail(java.
	 * lang.Integer, java.lang.Integer, byte[])
	 */
	@Override
	public byte[] createThumbnail(final Integer width, final Integer height, final String format, final byte[] imageBytes) throws IOException {

		if (imageBytes == null) {
			throw new NullPointerException("Cannot generate thumbnail with null bytes");
		}

		final InputStream inputStream = new ByteArrayInputStream(imageBytes);

		final Builder<? extends InputStream> th = Thumbnails.of(inputStream);
		th.outputFormat(format);
		th.antialiasing(Antialiasing.ON);
		th.alphaInterpolation(AlphaInterpolation.QUALITY);
		// th.dithering(Dithering.DISABLE);
		th.outputQuality(0.9f);
		th.rendering(Rendering.QUALITY);
		th.scalingMode(ScalingMode.PROGRESSIVE_BILINEAR);
		th.crop(Positions.CENTER);

		if ((width != null) && (height != null)) {
			th.size(width, height);
		} else if (width != null) {
			th.width(width);
			th.height(width);
		} else if (height != null) {
			th.height(height);
			th.width(height);
		}

		final ByteArrayOutputStream os = new ByteArrayOutputStream(imageBytes.length);
		th.toOutputStream(os);

		return os.toByteArray();
	}

}