title: Unable to open png device in loop
body: <p>I've been fiddling around with a function in R, where, long story short, I have a <code>for</code>-loop, and at each step, I save a plot using <code>png</code>, then immediately <code>readPNG</code> so that I can extract RGB information. I then make a second plot, then <code>readPNG</code> this so I can compare the RGB of the two images. 
  The problem is that I keep getting an error message about being unable to start the <code>png()</code> device, or to open the file for writing, after a number of loops (can be as few as a handful of loops, or as many as a few thousand).</p>
  
  <p>Here is really simplified code, but it has the bare essentials, and generates the error message:
  </p>
  
  <pre><code>testfun&lt;-function(beg,fini)
  {
   library(png)
   setwd("D://mydirectory")
   for (i in beg:fini)
   {
    png("test.png",width=277,height=277) #candidate image
    par(mai=c(0,0,0,0))
    plot(1,type="n",ann=FALSE,xlim=c(0,255),ylim=c(0,255),
           xaxt="n",yaxt="n",frame.plot=F)
    polygon(x=c(10,60,60),y=c(10,10,60),col="red")
    graphics.off()
  
    image&lt;-readPNG("test.png")
    #code where I get rgb values for original
  
    png("test2.png",width=277,height=277) #candidate image with diferent params
    par(mai=c(0,0,0,0))
    plot(1,type="n",ann=FALSE,xlim=c(0,255),ylim=c(0,255),
           xaxt="n",yaxt="n",frame.plot=F)
    polygon(x=c(10,60,60),y=c(10,10,60),col="blue")
    graphics.off()
  
    image&lt;-readPNG("test2.png")
    #code where I get rgb values for second image, and compare
   }
  }
  </code></pre>
  
  <p>And the error message:</p>
  
  <pre><code>Error in png("test.png", width = 277, height = 277) : 
    unable to start png() device
  In addition: Warning messages:
  1: In png("test.png", width = 277, height = 277) :
    Unable to open file 'test.png' for writing
  2: In png("test.png", width = 277, height = 277) : opening device failed
  </code></pre>
  
  <p>Originally I had <code>graphics.off()</code> as <code>dev.off()</code> but then thought maybe the loop was so fast that turning off one device wasn't fast enough before needing to be open again and it was getting 'confused' somehow. I also tried using <code>Sys.sleep(0.1)</code> after each <code>graphics.off</code>, but that didn't help either. Am I missing something stupid and obvious, or is this just a device bug?</p>