public BufferedImage errorImage ( String ... lines ) { if ( imageBuffer == null || imageBuffer . getWidth ( ) != imageWidth || imageBuffer . getHeight ( ) != imageHeight ) { imageBuffer = new BufferedImage ( imageWidth , imageHeight , BufferedImage . TYPE_INT_RGB ) ; } Graphics2D g = ( Graphics2D ) imageBuffer . getGraphics ( ) ; g . setBackground ( new Color ( 64 , 32 , 32 ) ) ; g . setColor ( new Color ( 255 , 64 , 64 ) ) ; g . clearRect ( 0 , 0 , imageWidth , imageHeight ) ; int maxLen = 0 ; for ( String line : lines ) { if ( line != null ) { for ( String innerLine : line . split ( "\n" ) ) { maxLen = Math . max ( innerLine . length ( ) , maxLen ) ; } } } int padding = 20 ; float sizeForWidth = 1.8f * ( imageWidth - padding - padding ) / maxLen ; // should use TextLayout float sizeForHeight = ( imageHeight - padding - padding ) / lines . length ; float lineHeight = Math . min ( 80 , Math . max ( 12 , Math . min ( sizeForWidth , sizeForHeight ) ) ) ; float fontSize = 0.8f * lineHeight ; Font font = g . getFont ( ) . deriveFont ( fontSize ) ; g . setFont ( font ) ; float y = fontSize + padding ; for ( String line : lines ) { if ( line != null ) { g . drawString ( line , padding , y ) ; y += lineHeight ; } } return imageBuffer ; }
Return an red image with the given text auto - sized to fit the current imageWidthximageHeight