1 /* 2 * Copyright (C) 2019 Ignite Realtime Foundation. All rights reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package org.jivesoftware.util; 17 18 import org.slf4j.Logger; 19 import org.slf4j.LoggerFactory; 20 21 import javax.imageio.ImageIO; 22 import java.io.ByteArrayInputStream; 23 import java.io.IOException; 24 import java.io.InputStream; 25 26 /** 27 * Utilities for working with graphics-related data. 28 * 29 * @author Guus der Kinderen, guus.der.kinderen@gmail.com 30 */ 31 public class GraphicsUtils 32 { 33 private static final Logger Log = LoggerFactory.getLogger( GraphicsUtils.class ); 34 35 /** 36 * Checks if the provided input stream represents an image. 37 * 38 * @param stream The data to be parsed. Cannot be null. 39 * @return true if the provided data is successfully identified as an image, otherwise false. 40 */ isImage( final InputStream stream )41 public static boolean isImage( final InputStream stream ) 42 { 43 try 44 { 45 // This attempts to read the bytes as an image, returning null if it cannot parse the bytes as an image. 46 return null != ImageIO.read( stream ); 47 } 48 catch ( IOException e ) 49 { 50 Log.debug( "An exception occurred while determining if data represents an image.", e ); 51 return false; 52 } 53 } 54 55 /** 56 * Checks if the provided byte array represents an image. 57 * 58 * @param bytes The data to be parsed. Cannot be null. 59 * @return true if the provided data is successfully identified as an image, otherwise false. 60 */ isImage( final byte[] bytes )61 public static boolean isImage( final byte[] bytes ) 62 { 63 if ( bytes == null ) 64 { 65 throw new IllegalArgumentException( "Argument 'bytes' cannot be null." ); 66 } 67 return isImage( new ByteArrayInputStream( bytes ) ); 68 } 69 } 70