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.
Here is what the above code is Doing:
1. It is creating a new thread.
2. It is passing the function which you want to run in the new thread.
3. It is passing the arguments to the function.
4. It is starting the thread.