public static BufferedImage createBufferedImage(int w,int h,Color background) throws OutOfMemoryError {
  BufferedImage result=null;
  if (w > 0 && h > 0) {
    Runtime runtime=Runtime.getRuntime();
    long maxMemory=runtime.maxMemory();
    long allocatedMemory=runtime.totalMemory();
    long freeMemory=runtime.freeMemory();
    long totalFreeMemory=(freeMemory + (maxMemory - allocatedMemory)) / 1024;
    int bytes=4;
    long memoryRequired=w * h * bytes / 1024;
    if (memoryRequired <= totalFreeMemory) {
      int type=(background != null) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
      result=new BufferedImage(w,h,type);
      if (background != null) {
        Graphics2D g2=(Graphics2D)result.createGraphics();
        clearRect(g2,new Rectangle(w,h),background);
        g2.dispose();
      }
    }
 else {
      throw new OutOfMemoryError("Not enough memory for image (" + w + " x "+ h+ ")");
    }
  }
  return result;
}

public static BufferedImage createBufferedImage ( int w , int h , Color background ) throws OutOfMemoryError { BufferedImage result = null ; if ( w > 0 && h > 0 ) { Runtime runtime = Runtime . getRuntime ( ) ; long maxMemory = runtime . maxMemory ( ) ; long allocatedMemory = runtime . totalMemory ( ) ; long freeMemory = runtime . freeMemory ( ) ; long totalFreeMemory = ( freeMemory + ( maxMemory - allocatedMemory ) ) / 1024 ; int bytes = 4 ; long memoryRequired = w * h * bytes / 1024 ; if ( memoryRequired <= totalFreeMemory ) { int type = ( background != null ) ? BufferedImage . TYPE_INT_RGB : BufferedImage . TYPE_INT_ARGB ; result = new BufferedImage ( w , h , type ) ; if ( background != null ) { Graphics2D g2 = ( Graphics2D ) result . createGraphics ( ) ; clearRect ( g2 , new Rectangle ( w , h ) , background ) ; g2 . dispose ( ) ; } } else { throw new OutOfMemoryError ( "Not enough memory for image (" + w + " x " + h + ")" ) ; } } return result ; }
creates a buffered image for the given parameters . if there is not enough memory to create the image then a outofmemoryerror is thrown .
