Thanks again for all the suggestions, It seems like my problem is in the filewriteEx. It is returning a negative number (-25890) and the filelength is returning -1.
writepic = FilewriteEx (tempfile, lblb_out)
I don't know what can make that statement failed.