How to convert bam to fasta?

I have bam files and reference fasta. I want to get fasta sequence from bam file:
![see picture][1]

Is there a software that can do this?

  [1]: http://s22.postimg.org/hwdzkaktt/fasta.png
What the original poster needs is creating a consensus sequence out of BAM alignments. It is easy to misread that into the problem of extracting the read sequences from the BAM file.

See this for an answer: https://www.biostars.org/p/184944/#185560
(notably the title of this post is incorrect as well, the OP there wants FASTA file not FASTQ)

But note that the problem can be more complicated than what it initially seems. It only works in  ideal cases. 

In the most general case the SNPs may not resolve into a single consensus sequence because that is not how the SNP callers work. They optimize the SNPs for a local region and not against a consensus. 
In addition in many (most) cases you may have a population of cells hence SNPs may represent different DNA molecules. 

This is not to say that there is no value in producing a consensus but it is good to keep in mind the limitations of the the process.



