You can use threading to solve your problem. You can put your image writing function inside a new thread and then that task will get independent of your UI part and hence it will not lag. I have done it and let me know if you need any further help.