]> git.basschouten.com Git - openhab-addons.git/blob
f0416a7612d6d0bbafc8f1d24b66f31e6be396a1
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.nuvo.internal.communication;
14
15 import java.awt.AlphaComposite;
16 import java.awt.Graphics2D;
17 import java.awt.Image;
18 import java.awt.RenderingHints;
19 import java.awt.image.BufferedImage;
20 import java.io.ByteArrayInputStream;
21 import java.io.ByteArrayOutputStream;
22 import java.io.IOException;
23
24 import javax.imageio.ImageIO;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27
28 /**
29  * The {@link NuvoImageResizer} class contains methods for re-sizing album art
30  *
31  * @author Michael Lobstein - Initial contribution
32  */
33 @NonNullByDefault
34 public class NuvoImageResizer {
35     private static final String EXTENSION_JPG = "jpg";
36     private static final byte[] NO_IMAGE = { 0 };
37
38     public static byte[] resizeImage(byte[] inputImage, int width, int height) {
39         try {
40             BufferedImage image = ImageIO.read(new ByteArrayInputStream(inputImage));
41             Image originalImage = image.getScaledInstance(width, height, Image.SCALE_DEFAULT);
42
43             int type = ((image.getType() == 0) ? BufferedImage.TYPE_INT_ARGB : image.getType());
44             BufferedImage resizedImage = new BufferedImage(width, height, type);
45
46             Graphics2D g2d = resizedImage.createGraphics();
47
48             g2d.setComposite(AlphaComposite.Src);
49             g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
50             g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
51             g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
52
53             g2d.drawImage(originalImage, 0, 0, width, height, null);
54             g2d.dispose();
55
56             ByteArrayOutputStream baos = new ByteArrayOutputStream();
57             ImageIO.write(resizedImage, EXTENSION_JPG, baos);
58             return baos.toByteArray();
59         } catch (IOException e) {
60             return NO_IMAGE;
61         }
62     }
63 }