001package com.github.sarxos.webcam.util;
002
003import java.awt.image.BufferedImage;
004import java.io.ByteArrayOutputStream;
005import java.io.IOException;
006
007import javax.imageio.ImageIO;
008
009import com.github.sarxos.webcam.WebcamException;
010
011
012public class ImageUtils {
013
014        /**
015         * Graphics Interchange Format.
016         */
017        public static final String FORMAT_GIF = "GIF";
018
019        /**
020         * Portable Network Graphic format.
021         */
022        public static final String FORMAT_PNG = "PNG";
023
024        /**
025         * Joint Photographic Experts Group format.
026         */
027        public static final String FORMAT_JPG = "JPG";
028
029        /**
030         * Bitmap image format.
031         */
032        public static final String FORMAT_BMP = "BMP";
033
034        /**
035         * Wireless Application Protocol Bitmap image format.
036         */
037        public static final String FORMAT_WBMP = "WBMP";
038
039        /**
040         * Convert {@link BufferedImage} to byte array.
041         * 
042         * @param image the image to be converted
043         * @param format the output image format
044         * @return New array of bytes
045         */
046        public static byte[] toByteArray(BufferedImage image, String format) {
047
048                byte[] bytes = null;
049                ByteArrayOutputStream baos = new ByteArrayOutputStream();
050
051                try {
052                        ImageIO.write(image, format, baos);
053                        bytes = baos.toByteArray();
054                } catch (IOException e) {
055                        throw new WebcamException(e);
056                } finally {
057                        try {
058                                baos.close();
059                        } catch (IOException e) {
060                                throw new WebcamException(e);
061                        }
062                }
063
064                return bytes;
065        }
066}