Fix memory leak in context and image ref