2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.lghombot.internal;
15 import java.awt.image.BufferedImage;
16 import java.io.ByteArrayOutputStream;
17 import java.io.IOException;
19 import javax.imageio.ImageIO;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.openhab.core.library.types.RawType;
23 import org.openhab.core.types.State;
24 import org.openhab.core.types.UnDefType;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
29 * The {@link CameraUtil} is responsible for parsing the raw yuv 422 image from a LG HomBot.
31 * @author Fredrik Ahlström - Initial contribution
34 public class CameraUtil {
36 private static final Logger LOGGER = LoggerFactory.getLogger(CameraUtil.class);
38 private CameraUtil() {
39 // No need to instance this class.
43 * This converts a non-interleaved YUV-422 image to a JPEG image.
45 * @param yuvData The uncompressed YUV data
46 * @param width The width of image.
47 * @param height The height of the image.
48 * @return A JPEG image as a State
50 static State parseImageFromBytes(byte[] yuvData, int width, int height) {
51 final int size = width * height;
53 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
55 for (int i = 0; i < size; i++) {
56 double y = yuvData[i] & 0xFF;
57 double u = yuvData[size + i / 2] & 0xFF;
58 double v = yuvData[(int) (size * 1.5 + i / 2.0)] & 0xFF;
60 int r = Math.min(Math.max((int) (y + 1.371 * (v - 128)), 0), 255); // red
61 int g = Math.min(Math.max((int) (y - 0.336 * (u - 128) - 0.698 * (v - 128)), 0), 255); // green
62 int b = Math.min(Math.max((int) (y + 1.732 * (u - 128)), 0), 255); // blue
64 int p = (r << 16) | (g << 8) | b; // pixel
65 image.setRGB(i % width, i / width, p);
68 ByteArrayOutputStream baos = new ByteArrayOutputStream();
70 if (!ImageIO.write(image, "jpg", baos)) {
71 LOGGER.debug("Couldn't find JPEG writer.");
73 } catch (IOException e) {
74 LOGGER.info("IOException creating JPEG image.", e);
76 byte[] byteArray = baos.toByteArray();
77 if (byteArray != null && byteArray.length > 0) {
78 return new RawType(byteArray, "image/jpeg");
80 return UnDefType.UNDEF;